模拟掷骰子游戏,非常初学者


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!");

    }

不好意思。。。这可能是一个愚蠢的问题,但我对java
非常初学者我应该创建一个掷骰子游戏。规则很简单,如果计算机的数字大于玩家,则计算机获胜,如果玩家的数字较大,则玩家获胜。我必须使用 If 语句创建它。但是我收到错误说"无法从静态上下文引用非静态变量",并且还收到错误说"找不到交易品种获胜者"我不知道该怎么做。非常感谢您的帮助..

这里有几个问题,第一个播放器,计算机是非静态变量,你想用静态方法(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. "winner"变量是骰子函数的本地变量,无法在 main 中访问。

修改上述两点的代码,它应该可以工作。 公开课骰子 { 静态 int 播放器; 静态 int 计算机;

    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;
    }
}

最新更新