public class Dice
{
int player;
int computer;
public static void main (String[]args)
{
player = 1 + (int)((Math.random()*7));
computer = 1 + (int)((Math.random()*7));
diceRoll();
System.out.println("You rolled a " + player);
System.out.println("Computer rolled a " + computer);
System.out.println("And the winner is" + winner);
}
public static void diceRoll()
{
boolean winner = player > computer;
if (winner)
System.out.println("You won!");
if (!winner)
System.out.println("You lost!");
}
对不起......这可能是个愚蠢的问题,但我是初学者 我应该创建一个骰子滚动游戏。规则很简单,如果计算机的数量大于玩家,则计算机获胜,如果玩家的数量较大,则玩家获胜。我必须使用If语句来创建它。 但是我得到的错误是"非静态变量不能从静态上下文中引用"而且我得到的错误是"找不到符号赢家" 我不知道该怎么做 非常感谢你的帮助..
答案 0 :(得分:5)
这里有几个问题,第一个播放器,计算机是非静态变量,你想用静态方法(main)访问它们,所以让它们保持静态。 第二个在diceRoll()方法之外声明获胜者,这样你就可以在main中使用它来制作那个静态。 第三,让胜利者成为胜利者名字。
public class Dice {
static int player;
static int computer;
static String winner;
public static void main(String[] args) {
player = 1 + (int) ((Math.random() * 7));
computer = 1 + (int) ((Math.random() * 7));
diceRoll();
System.out.println("You rolled a " + player);
System.out.println("Computer rolled a " + computer);
System.out.println("And the winner is" + winner);
}
public static void diceRoll() {
if(player > computer){
System.out.println("You won!");
winner = "Player";
}else{
System.out.println("You lost!");
winner = "Computer";
}
}
}
答案 1 :(得分:2)
修改上述两点的代码,它应该有效。 公共课骰子 { static int player; static int computer;
public static void main (String[]args)
{
player = 1 + (int)((Math.random()*7));
computer = 1 + (int)((Math.random()*7));
boolean winner= diceRoll();
System.out.println("You rolled a " + player);
System.out.println("Computer rolled a " + computer);
System.out.println("And the winner is" + winner);
}
public static boolean diceRoll()
{
boolean winner = player > computer;
if (winner)
System.out.println("You won!");
if (!winner)
System.out.println("You lost!");
return winner;
}
}