非静态方法不能从静态上下文中引用

时间:2010-04-22 21:16:15

标签: java static

首先是一些代码:

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) ;
                      ^

究竟出了什么问题?该错误消息“非静态方法无法从静态上下文引用”是什么意思?

4 个答案:

答案 0 :(得分:27)

您使用nextInt静态呼叫Random.nextInt

而是创建一个变量Random r = new Random();,然后调用r.nextInt(10)

结账时绝对值得:

更新

你真的应该替换这一行,

Random Random = new Random(); 

用这样的东西,

Random r = new Random();

如果你使用变量名作为类名,你会遇到很多问题。此外,作为Java约定,使用变量的小写名称。这可能有助于避免一些混乱。

答案 1 :(得分:2)

您正试图在自己的类上调用实例方法

你应该这样做:

    Random rand = new Random();
    int a = 0 ; 
    while (!done) { 
        int a = rand.nextInt(10) ; 
    ....

相反

我在这里告诉你stackoverflow.com/questions/2694470/whats-wrong...

答案 2 :(得分:1)

在Java中,静态方法属于类而不是实例。这意味着您无法从静态方法调用其他实例方法,除非在您在该方法中初始化的实例中调用它们。

以下是您可能想要做的事情:

public class Foo
{
  public void fee()
  {
     //do stuff  
  }

  public static void main (String[]arg) 
  { 
     Foo foo = new Foo();
     foo.fee();
  } 
}

请注意,您正在从已实例化的实例运行实例方法。您不能直接从静态方法调用类实例方法,因为没有与该静态方法相关的实例。

答案 3 :(得分:0)

违反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;
    }
  }
}