我很困惑何時使用public static void xxx()
和public void xxx()
。我得到的錯誤是在主類中。靜態和非靜態錯誤
generateRandomNumber();
The error : (error: non-static method generateRandomNumber() cannot be referenced from a static context)
getUserInput();
he error : (error: non-static method getUserInput() cannot be referenced from a static context)
的getResult();
The error : (error: non-static method getResult() cannot be referenced from a static context)
public class HighLowGame {
int randomNumber;
int guess;
public void generateRandomNumber(){
randomNumber = (0+(int)(Math.random() * ((0 - 99) + 1)));
}
public void getUserInput(){
guess = Integer.parseInt(JOptionPane.showInputDialog(
null,
"Plaese input"));
}
public String getResult(){
if(randomNumber<guess){
return "Your number is bigger than magic number";
}
else if (randomNumber>guess) {
return "Your number is smaller than magic number";
}
else {
return "You are correct! "+randomNumber;
}
}
public static void main(String[] args){
generateRandomNumber();
getUserInput();
getResult();
}
}
憑經驗:如果字段/方法屬於類本身它是靜態的。如果它屬於類的一個實例,它不是靜態的。由於非靜態屬於一個實例,因此您需要一個實例來訪問它們。 – jlordo 2013-02-12 11:03:01
'main()'是靜態的。如果不使用這些靜態方法中屬於這些方法的類的實例,則不能調用非靜態方法(或字段)。 – Lion 2013-02-12 11:03:36
[java:非靜態變量不能從靜態上下文中引用錯誤]的可能重複(http://stackoverflow.com/questions/926822/java-non-static-variable-cannot-be-referenced-from-a -static-context-error) – EJP 2013-02-12 20:52:09