嗨,我很確定這是一個初學JAVA問題。我跑了我的編譯器,它顯示有錯誤試圖從另一個類調用方法而不是獲取錯誤。 JAVA
Cannot make a static reference to the non-static method roll() from the type Die
在我的主要方法的最後一行。
我想要做的是滾動兩個骰子並添加它們。我的問題是這條線有什麼問題
以及我該如何解決這個問題?在此先感謝
/** main method
Die myDie1 = new Die();
Die myDie2 = new Die();
for(int roll=1;roll<=total;roll++)
{
counts[(Die.roll()+Die.roll())]++; //<--error here
}
**/
骰子方法
public class Die
{
private final int MAX = 6; // maximum face value
private int faceValue; // current value showing on the die
//-----------------------------------------------------------------
// Constructor: Sets the initial face value.
//-----------------------------------------------------------------
public Die()
{
faceValue = 1;
}
//-----------------------------------------------------------------
// Rolls the die and returns the result.
//-----------------------------------------------------------------
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
//-----------------------------------------------------------------
// Face value mutator.
//-----------------------------------------------------------------
public void setFaceValue (int value)
{
faceValue = value;
}
//-----------------------------------------------------------------
// Face value accessor.
//-----------------------------------------------------------------
public int getFaceValue()
{
return faceValue;
}
//-----------------------------------------------------------------
// Returns a string representation of this die.
//-----------------------------------------------------------------
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
可能重複的[不能靜態引用非靜態方法](http://stackoverflow.com/questions/4969171/cannot-make-static-reference-to-non-static-method) – 2014-10-29 06:02:08