如何让猜猜游戏重新开始。而循环Java

时间:2015-01-11 21:00:55

标签: java

我正在练习Java,我试图制作一个猜测游戏,但我希望游戏在用户不能正确猜出数字时再次要求输入。当我猜错了数字时,循环只是连续猜测数字,直到数字是正确的并且游戏结束。

import java.util.*;
class GuessGame {



private Scanner userInput = new Scanner(System.in);

public GuessGame(){
    System.out.println("~~~Guess Game~~~");
    System.out.println("~~~Guess a number between 0 and 9~~~");
}

int guessedNumber = 0;

public void gameStart(){

    System.out.println("Guess a number: ");
    boolean guessedRight = false;
    boolean gameOn = true;
    int userNumber = userInput.nextInt();
    while(gameOn){
        guessedNumber = userNumber;
        int randomNumber = (int) (Math.random() * 10);
        if(randomNumber == guessedNumber){
            guessedRight = true;
        }
        if(guessedRight){
            System.out.println("You guessed " + guessedNumber);
            System.out.println("The number is " + randomNumber);
            System.out.println("You won!!!");
            System.out.println("Game Over!!!");
            break;
        }else{
            System.out.println("You guessed " + guessedNumber);
            System.out.println("The number is " + randomNumber);
            System.out.println("Try again!!!");

        }
    }
   }
}

2 个答案:

答案 0 :(得分:1)

int userNumber = userInput.nextInt();行负责获取用户从输入行输入的数字。在while循环内移动此行将在每次循环运行时询问一个数字(如果用户第一次猜对,则只需一次)。

答案 1 :(得分:0)

只需从循环中调用该方法:

public GuessGame(){
    while(true) {
        System.out.println("~~~Guess Game~~~");
        System.out.println("~~~Guess a number between 0 and 9~~~");
        gameStart();
    }
}

只要gameStart()方法存在,就会重启游戏。 (这是用户猜对了正确的数字)