【发布时间】:2018-12-22 06:06:13
【问题描述】:
尝试创建一个循环,如果输入 1 2 3 4 5 以外的任何内容或发生输入不匹配,该循环将重复。我很新尝试和我的老师说我需要经常使用它们来完成这项任务。我不确定为什么这会无限循环。我已经玩了好几个小时了,我认为我拥有的每一个不同的解决方案都以一个永远打印的重复循环结束。感谢任何可以提供帮助的人。
do {
System.out.printf("Please enter the number corresponding with with what would like to edit: %n1. Title%n2. Author%n3. Location%n4. Book Type%n5. Book Status%n");
try {
x = scan.nextInt();
if (x != 1 && x != 2 && x != 3 && x != 4 && x != 5) {
System.out.println("you must enter either 1 2 3 4 5");
}
} catch (Exception ex) {
System.out.println("you must enter either 1 2 3 4 5");
x = 0;
}
} while (x != 1 && x != 2 && x != 3 && x != 4 && x != 5);
【问题讨论】:
-
将
scan.nextLine()添加到您的catch。当前行为:给我下一个 int,没有一个所以抛出异常,给我下一个 int ...它仍然不是 int ... -
@SukhpalSingh
x != 1 || x != 2对于x的所有值都为真。&&在这里似乎是正确的。 -
我的回答是否回答了您的问题?如果是这样,请考虑通过单击该复选标记接受它!