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

Dav*_*vid 17 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 
Run Code Online (Sandbox Code Playgroud)

这是错误消息:

TicTacToe.java:85: non-static method nextInt(int) cannot be referenced from a static context
            a = Random.nextInt(10) ;
                      ^
Run Code Online (Sandbox Code Playgroud)

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

Ant*_*ney 27

您正在nextInt使用静态调用Random.nextInt.

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

结账时绝对值得:

更新:

你真的应该替换这条线,

Random Random = new Random(); 
Run Code Online (Sandbox Code Playgroud)

有这样的,

Random r = new Random();
Run Code Online (Sandbox Code Playgroud)

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