我的程序中使用了以下代码:
do {
if (numOfItems == 3 || numOfItems == 5 || numOfItems == 7 || numOfItems == 9) {
addItems(numOfItems);
} else {
System.out.println("That number is out of range.");
System.out.println("Please choose an odd number in the range of [1, 10] exclusively:");
numOfItems = scan.nextInt();
}
} while (numOfItems != 3 || numOfItems != 5 || numOfItems != 7 || numOfItems != 9);
,在运行时,不断重复我只想发生一次的方法。如何使循环不断重复验证,但只运行一次方法?
答案 0 :(得分:3)
替换
while (numOfItems != 3 || numOfItems != 5 || numOfItems != 7 || numOfItems != 9);
与
while (numOfItems != 3 && numOfItems != 5 && numOfItems != 7 && numOfItems != 9);
<强>更新强>
从您的评论到答案,您似乎需要执行以下操作:
do {
numOfItems = scan.nextInt();
if (numOfItems == 3 || numOfItems == 5 || numOfItems == 7 || numOfItems == 9) {
addItems(numOfItems);
} else {
System.out.println("That number is out of range.");
System.out.println("Please choose an odd number in the range of [1, 10] exclusively:");
}
} while (numOfItems != 3 && numOfItems != 5 && numOfItems != 7 && numOfItems != 9);
但是,您可以将其优化为以下内容:
while ((numOfItems = scan.nextInt() != 3) && numOfItems != 5 && numOfItems != 7 && numOfItems != 9) {
System.out.println("That number is out of range.");
System.out.println("Please choose an odd number in the range of [1, 10] exclusively:");
}
addItems(numOfItems);
答案 1 :(得分:1)
您可能想要更正
while (numOfItems != 3 || numOfItems != 5 || numOfItems != 7 || numOfItems != 9);
因为,它始终是 true 。
如果您始终要执行do..while
语句块,则可以删除此(do{...}
)条件。 (“......我只想发生一次”)