gpt4 book ai didi

java - Do-While 循环在程序运行时连续打印

转载 作者:行者123 更新时间:2023-11-29 08:39:02 24 4
gpt4 key购买 nike

我的程序中使用了以下代码:

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);

它在运行时不断重复我只想发生一次的方法。如何使循环不断重复以进行验证,但只运行该方法一次?

最佳答案

替换

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);

关于java - Do-While 循环在程序运行时连续打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41657721/

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