[英]Do-While Loop continuously prints when Program is ran
我的程序中使用了以下代碼:
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);
您可能要糾正
while (numOfItems != 3 || numOfItems != 5 || numOfItems != 7 || numOfItems != 9);
從此,這將永遠是正確的 。
如果您始終想執行語句的do{...}
塊,則可以擺脫this( do..while
)條件。 (“ ...我只想發生一次”)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.