[我正在尝试通过使用各种方法来掷骰子,比较并总结骰子来模拟Yahtzee游戏。
这是一项作业,我需要使用这三种静态方法来完成所有工作。
[当我尝试运行代码但是遇到此错误时
exit status 1
Main.java:6: error: non-static method rollDice(int[]) cannot be referenced from a static context
rollDice(dice);
^
Main.java:7: error: non-static method rollDice(int[]) cannot be referenced from a static context
dice= rollDice(dice);
^
2 errors
我曾尝试运行这些方法,然后再将其赋值给变量,但这似乎不起作用。这是我完整的代码:
class Main {
public static void main(String[] args) {
// int array to hold 5 dice
int dice[] = new int[5];
rollDice(dice);
dice= rollDice(dice);
fiveOfaKind(dice);
int points = fiveOfaKind(dice);
getChance(dice,points);
int printpoint = getChance(dice,points);
// You may roll the dice up to 3 times to try to get 5 of a Kind
// If you get 5 of a Kind, stop if not keep trying.
// If you do not get 5 of a Kind after the 3rd roll, you must take the
// CHANCE score.
System.out.println("Your score is " + printpoint);
}// end of main method
public int[] rollDice(int dice[]){
// generate 5 random numbers / update dice array
for (int i = 0; i < dice.length; i++) {
dice[i] = (int)(Math.random() * 6 + 1);
}
return dice;
}// end of rollDice - rolls 5 dice and puts them in an array
// All 5 dice must be rolled each time
public static int fiveOfaKind(int dice[]){
int pts = 0;
int rNum=0;
for(int i=0; rNum<3; rNum++){
if(dice[0]==dice[1]&&dice[1]==dice[2]&&dice[2]==dice[3]&&dice[3]==dice[4]&&dice[4]==dice[5]&&dice[5]==dice[6]){
pts=50;
}
else if(rNum==3){
pts=0;
}
else{
int[] rollDice;
}
}//end of forloop
// use Array dice - evaluate if all elements are equal
// if true = pts = 50
// if false - pts = 0
return pts;
}// end of fiveOfaKind - evaluates the dice roll to see if all 5 are equal
// Returns 50 points if they do
public static int getChance(int dice[], int points){
if(points<50){
points=0;
for (int i = 0; i < dice.length; i++) {
points+=dice[i];
}
}
// use Array dice - sum the elements of the Array
// pys = calculated value of the sum
int p = points;
return p;
}// end of getChance - adds the total value of the dice
// Returns the total points calculated
}// end of class
您需要将rollDice()
方法设置为静态。非静态方法不能从静态方法中调用。如果要调用非静态方法,则必须使用类的实例来调用该方法。
简单地说,静态方法/字段更像是与该类关联的属性,并且可以在该类的对象之间共享。
public int [] rollDice方法不存在,除非您创建包含该方法的类的对象,因为它是非静态的。非静态方法仅与您创建的每个对象相关联。因此,您创建的对象将具有自己的属性集,这些属性集不依赖于其他对象,并且您可以使用这些属性来维护该对象内的状态。
简单修复:
使方法rollDice保持静态(根据您的程序结构推荐)
或
调用这样的方法:
Main obj = new Main();
obj.rollDice(dice);
如果您不了解两者之间的区别,我建议您阅读本文(Static vs Non-Static)。从面向对象编程的角度理解它真的很重要。