我需要结束游戏或继续上课的While循环



对于我的班级,我们需要制作一个骰子游戏,我制作了我版本的战争,我需要一点帮助来完成它。我需要显示最后的分数,如果我能以某种方式显示分数之间的差异,我会喜欢的。我也不知道如何结束循环游戏。

public class Game {
    public static void main(String[] args) 
       {
        Dice myDie = new Dice();
        Dice CompDie= new Dice();
        int player =0;
        int computer =0;
        boolean gameOver;
        do
        {
            int[] scores = new int[3];
            gameOver = false;
            while(!gameOver)
            {
                myDie.roll();
                System.out.println("You rolled a " + myDie.getValue());
                player = myDie.getValue();
                CompDie.roll();
                System.out.println("Computer rolled a " + CompDie.getValue());
                computer = CompDie.getValue();
                checkResults(player, computer, scores);
                printResults(scores);
                // ask player if want to continue enter Y to continue
                System.out.println("Do you want to continue playing enter Y if so");    // I need to end loop here


            }
       }while(keepPlaying());




       }
    public static boolean keepPlaying()
    {
        Scanner readIn = new Scanner(System.in);
        boolean playAgain = false; 
        System.out.println("Do you want to play again?");
        String answer = readIn.nextLine().toUpperCase();
        char ans = answer.charAt(0);
        if(ans == 'Y')
            playAgain = true;
        return playAgain;
    }
    public static void checkResults(int player, int computer, int[] scores)
    {
        if(player > computer)
        {
            scores[1]++;
        }
        else if(player < computer)
        {
            scores[2]++;
        }
        else
        {
            scores[0]++;
        }
    }
    public static void printResults(int[] list)
    {
        System.out.println("     Ties    Player   Computer");
        for (int i = 0; i < list.length; i++)
        {
            System.out.printf("%8d", list[i]);
        }
        System.out.println();
    }
}
 while(!gameOver)
        {
        }

这个循环是不必要的,而且永远不会停止。如果你仍然想要它,当你想退出时,你需要设置gameOver=true。

要显示分数之间的差异,只需将分数相互减去并打印即可。System.out.println(Math.abs(score[1] - score[2]));像这样的东西。

最新更新