Java boolean条件while循环似乎忽略了if语句?

时间:2014-11-12 19:59:17

标签: java loops while-loop

在这附近 - if (code<10 || code>99)似乎是个问题。当输入一个超出范围的数字时,循环会无限延续,似乎忽略了这个条件。我尝试了System.exit(0),虽然这样做我想尝试并使用while循环来停止代码。

import java.util.*;
public class LockPicker {

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        Random r = new Random();
        boolean stop = false; 
        while (!stop) {
            System.out.print("What is the unlock code? ");
            int code = kb.nextInt();
            if (code<10 || code>99) {
                System.out.println("Your number must be between 10 and 99");
                stop = !stop;
            }

            System.out.println("Picking the lock...");
            System.out.println("");
            int x = -1, counter = 0;
            while (x!=code) {
                x = r.nextInt(90)+10;
                System.out.println(x);
                counter++;
            }
            System.out.println("That took only "+counter+" tries to pick the lock!");
            stop = !stop;
        }
    }
}

2 个答案:

答案 0 :(得分:3)

您不需要stop变量。您可以使用breakcontinue

Random r = new Random();
while (true) {
    System.out.print("What is the unlock code? ");
    int code = kb.nextInt();
    if (code < 10 || code > 99) {
        System.out.println("Your number must be between 10 and 99");
        continue;
    }

    System.out.println("Picking the lock...");
    System.out.println("");
    int x = -1, counter = 0;
    while (x != code) {
        x = r.nextInt(90) + 10;
        System.out.println(x);
        counter++;
    }
    System.out.println("That took only " + counter
            + " tries to pick the lock!");
    break;
}

continue将跳过迭代并转到while循环以再次提示用户输入数字。 <{1}}将在找到匹配时结束break循环。

答案 1 :(得分:0)

在您的号码超出所需范围的情况下,您将切换两次停止。这使你的循环永远运行。您确实希望将stop设置为true,而不是将其切换。