问题描述
首先是一些代码:
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) ;
^
究竟出了什么问题?该错误消息非静态方法无法从静态上下文引用是什么意思?
What exactly went wrong? What does that error message "non static method cannot be referenced from a static context" mean?
推荐答案
您使用 nextInt > Random.nextInt 。
You are calling nextInt
statically by using Random.nextInt
.
相反,创建一个变量, Random r = new Random();
然后拨打 r.nextInt(10)
。
Instead, create a variable, Random r = new Random();
and then call r.nextInt(10)
.
检查时绝对值得out:
It would be definitely worth while to check out:
- What is the reason behind "non staticmethod cannot be referenced from a static context"?
你真的应该替换这一行,
You really should replace this line,
Random Random = new Random();
有这样的东西,
Random r = new Random();
如果你使用变量名作为类名,你会遇到很多问题。此外,作为Java约定,使用变量的小写名称。这可能有助于避免一些混淆。
If you use variable names as class names you'll run into a boat load of problems. Also as a Java convention, use lowercase names for variables. That might help avoid some confusion.
这篇关于非静态方法无法从静态上下文中引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!