简体   繁体   English

Java 输入某些字符时重播

[英]Java replay when certain character typed

When number 0 is typed after the guess is correct, it should replay the game.当猜对后输入数字 0 时,它应该重玩游戏。 It just returns the message "0 to play again and 1 to quit"它只是返回消息“0 再次播放,1 退出”

public static void main(String[] args) {
    boolean game = true; //true means the game will continue playing, false stops the game
    Scanner input = new Scanner(System.in);
    System.out.println("Guess: ");
    while (game) {
        HiLo mainGame = new HiLo();
        mainGame.generateRandomNumber();
        boolean guessCorrect = false;
        while (!guessCorrect) {
            int inputted = input.nextInt();
            if (inputted == 101) {
                guessCorrect = true;
                System.out.println("quitted");
            }
            System.out.println(mainGame.checkGuess(inputted));
            mainGame.getGuessCounter();
            if (mainGame.checkGuess(inputted) == "Correct! You got it right!") {
                guessCorrect = true;
                System.out.println("Correct after " + mainGame.getGuessCounter() + " guesses");
            }
        }
        while (guessCorrect = true) {
            System.out.println("Would you like to play again? (0 : YES) (1 : NO)");
            System.out.println("Your answer: ");
            int answer = input.nextInt();
            //issues with inputting 0 and restarting game
            if (answer == 0) {
                game = true;
            }
            else if (answer == 1) {
                guessCorrect = true;
                System.out.println("Game Over");
            }
            else {
                System.out.println("Error, can't understand the meaning"); 
                guessCorrect = false;
            }
        }
    }
}

Change while (guessCorrect = true) to while (guessCorrect) .while (guessCorrect = true)更改为while (guessCorrect) Set guessCorrect to false to exit the while (guessCorrect) loop and proceed to restarting or exiting the game.guessCorrect设置为false以退出while (guessCorrect)循环并继续重新启动或退出游戏。 Make sure to set the game to false if answer is not equal to 0 to exit the game.如果answer不等于0 ,请确保将game设置为false以退出游戏。

        while (guessCorrect) {
            System.out.println("Would you like to play again? (0 : YES) (1 : NO)");
            System.out.println("Your answer: ");
            int answer = input.nextInt();
            //issues with inputting 0 and restarting game
            if (answer == 0) {
                game = true;
            }
            else if (answer == 1) {
                System.out.println("Game Over");
                game = false;
            }
            else {
                System.out.println("Error, can't understand the meaning"); 
                game = false;
            }
            
            guessCorrect = false;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM