非静态方法不能从静态上下文引用
首先是一些代码:
import java.util.*; //... class TicTacToe { //... public static void main (String[]arg) { Random Random = new Random() ; toerunner () ; // this leads to a path of // methods that eventualy gets us to the rest of the code } //... public void CompTurn (int type, boolean debug) { //... boolean done = true ; int a = 0 ; while (!done) { a = Random.nextInt(10) ; if (debug) { int i = 0 ; while (i<20) { System.out.print (a+", ") ; i++; }} if (possibles[a]==1) done = true ; } this.board[a] = 2 ; } //... } //to close the class
这是错误消息:
TicTacToe.java:85: non-static method nextInt(int) cannot be referenced from a static context a = Random.nextInt(10) ; ^
究竟出了什么问题? 该错误消息“非静态方法无法从静态上下文引用”是什么意思?
您正在使用Random.nextInt
静态调用nextInt
。
相反,创建一个变量, Random r = new Random();
然后调用r.nextInt(10)
。
结账时绝对值得:
- “非静态方法无法从静态上下文中引用”背后的原因是什么?
更新:
你真的应该替换这条线,
Random Random = new Random();
有这样的,
Random r = new Random();
如果你使用变量名作为类名,你会遇到很多问题。 此外,作为Java约定,使用变量的小写名称。 这可能有助于避免一些混乱。
你试图在它自己的类上调用一个实例方法 。
你应该做:
Random rand = new Random(); int a = 0 ; while (!done) { int a = rand.nextInt(10) ; ....
代替
正如我在这里告诉你的stackoverflow.com/questions/2694470/whats-wrong …
在Java中,静态方法属于类而不是实例。 这意味着您无法从静态方法调用其他实例方法,除非在您在该方法中初始化的实例中调用它们。
这是您可能想要做的事情:
public class Foo { public void fee() { //do stuff } public static void main (String[]arg) { Foo foo = new Foo(); foo.fee(); } }
请注意,您正在从已实例化的实例运行实例方法。 您不能直接从静态方法调用类实例方法,因为没有与该静态方法相关的实例。
违反Java命名约定(变量名和方法名以小写开头,类名以大写开头)会导致您的混淆。
变量Random
仅在main
方法内“范围内”。 它不能被main
调用的任何方法访问。 从main
返回时,变量消失(它是堆栈帧的一部分)。
如果您希望类的所有方法都使用相同的Random
实例,请声明一个成员变量:
class MyObj { private final Random random = new Random(); public void compTurn() { while (true) { int a = random.nextInt(10); if (possibles[a] == 1) break; } } }