静态方法不能在非静态上下文中运行



我正在尝试通过使用各种方法来掷骰子,比较和总结骰子来模拟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);

如果您不知道两者之间的区别,我建议您阅读本文(静态与非静态(。从面向对象编程的角度来理解它非常重要。

静态方法是通用的,并且对于所有对象和它们共享的类都是相同的,对于它们来说,仅使用类调用函数就足够了,但另一方面,对于非静态方法,创建该类的对象很重要,因为它们与对象相关联,并且只能使用类的对象

所以你需要制作一个类 Main 的函数,然后用它来调用 rollDice 函数

例如:
Main ob1=new Main((;

ob1.rollDice(dice);

最新更新