无法成功重新循环while循环

时间:2017-02-14 05:05:20

标签: java if-statement while-loop conditional

我在以下代码中的目标是不断猜测,直到用户猜出正确的数字或​​退出。要退出,我能够轻松摆脱我的循环,但是当我尝试继续循环时,它不能正常工作。首先它需要多个输入,然后还完全重新生成我的数字,而我想要做的是继续猜测(询问用户)SAME随机数。 以下是我的代码:

public class Test {
public static void main(String[] args) {
    int count, randNum, guess;
    count = 0;
    Scanner scan = new Scanner(System.in);

    while (true) {
        Random rand = new Random();
        randNum = rand.nextInt(100) + 1;
        System.out.println("Guess a number b/w 1 and 100");
        guess = scan.nextInt();
        count += 1;

        if (guess == randNum) {
            System.out.println("Correct guess.");
            System.out.println("It took " + count + " tries to guess the right number");
            System.out.println("Would you like to play again? ");
            System.out.println("Press any letter to play again or q to quit: ");
            if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
                break;
            }
            else{
                continue;
            }
        }
        if (guess > randNum) {
            System.out.println("Your guess is bigger than actual number. Would you like to try again?");
            System.out.println("Press q to quit or any other letter to try again");
            if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
                break;
            }
            else {
                continue;
            }
        }
        else if (guess < randNum) {
            System.out.println("Your guess is smaller than actual number. Would you like to try again?");
            System.out.println("Press q to quit or any other letter to try again");
            if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
                break;
            }
            else  {
                    continue;
                }
            }

        }

}

}

2 个答案:

答案 0 :(得分:1)

生成随机数的代码应该在while语句之前。当您调用continue时,它会返回到while块的第一行,从而生成另一个随机数。

答案 1 :(得分:1)

声明int randNum的语句在while循环中,因此每次while循环重复时,都会声明(再次)该数字并将其设置为1到100之间的值。

如果要阻止这种情况,请声明变量并使用while循环外的随机值对其进行初始化。

一个小小的注意事项:通过初始化while循环内部的变量,您可以比您想要的更多地限制其范围。每次循环时,您创建的上一个randNum不再存在,然后创建一个新的。基本上,如果您希望它更永久,请在循环外部初始化它。

此外,如果您只是希望它第一次要求1到100之间的数字,请将其移到循环之外。然而,这取决于您是否希望每次询问或仅询问一次。

//…
public static void main(String[] args) {
    int count, randNum, guess;
    count = 0;
    Scanner scan = new Scanner(System.in);
    Random rand = new Random();
    randNum = rand.nextInt(100) + 1;
    System.out.println("Guess a number b/w 1 and 100");            
    while (true) {
        /*Random rand = new Random();
        randNum = rand.nextInt(100) + 1;
        System.out.println("Guess a number b/w 1 and 100");*/

        guess = scan.nextInt();
        count += 1;
        //…