gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:35:43 25 4
gpt4 key购买 nike

在这附近 - 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;
}
}
}

最佳答案

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

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 循环以再次提示用户输入数字。当找到匹配项时,break 将结束 while 循环。

关于Java boolean 条件while循环似乎忽略了if语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26895496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com