4 回答

TA貢獻1828條經驗 獲得超4個贊
您應該嘗試使用“真正的終止條件”來終止循環while
(或任何與此相關的循環);它更干凈,應該更容易被其他人理解。
在你的情況下,我認為最好有一個do
-while
循環,圍繞這個邏輯有一些條件:num % 2 == 0
,以及一個用于處理用戶輸入/驗證的內部while
循環。

TA貢獻1797條經驗 獲得超4個贊
我沒有完全遵循您想要的條件,因為除非有其他選項,否則 擁有繼續條件和終止條件是沒有意義的。
如果用戶輸入,您希望用戶做什么3
,4
或者5
?退出代碼還是繼續代碼?好吧,如果默認是退出,那么您不需要退出代碼,2
因為它已經退出了!如果默認是繼續,則不需要繼續1
,只需要退出2
。因此,在這種情況下兩者都做是沒有意義的。
以下是使用do while
循環的修改后的代碼,以確保循環至少進入1 次:
int x;
do {
System.out.println("Enter a number to check whether or not it is odd or even");
Scanner s = new Scanner(System.in);
int num = s.nextInt();
if (num % 2 == 0)
System.out.println("The number is even");
else
System.out.println("The number is odd");
//trying to figure out how to get the code to terminate if you put in a value that isn't a number
System.out.println("Type 1 to check another number, anything else to terminate.");
if (!s.hasNextInt()) {
break;
}
else {
x = s.nextInt();
}
} while(x == 1);
}
請注意,我添加了一個檢查來!s.hasNextInt()檢查用戶是否輸入了除 an 之外的任何內容,并且在這些情況下int將通過從循環中終止而不拋出 an 來終止(這與在本例中終止程序相同)。Exceptionbreak
如果x是有效整數,則將x設為該值,然后循環條件檢查是否x為1。如果x不是1,則循環終止,如果是,則將再次繼續循環。

TA貢獻1848條經驗 獲得超2個贊
您可以嘗試的另一件事是,您可以繼續要求用戶輸入正確的輸入,并且只有在他們這樣做時才繼續操作,而不是退出程序。我不知道你的要求是什么,但如果你想遵循良好的代碼實踐,那么你不應該僅僅因為用戶輸入了錯誤的輸入而終止你的程序。想象一下,如果你用谷歌搜索一個有拼寫錯誤的單詞,然后谷歌就關閉了。
無論如何,這就是我的做法
import java.util.Scanner;
public class oddoreven {
public static void main(String[] args) {
int num;
int x = 1;
while (x == 1) {
System.out.println("Enter a number to check whether or not it is odd or even");
Scanner s = new Scanner(System.in);
boolean isInt = s.hasNextInt(); // Check if input is int
while (isInt == false) { // If it is not int
s.nextLine(); // Discarding the line with wrong input
System.out.print("Please Enter correct input: "); // Asking user again
isInt = s.hasNextInt(); // If this is true it exits the loop otherwise it loops again
}
num = s.nextInt(); // If it is int. It reads the input
if (num % 2 == 0)
System.out.println("The number is even");
else
System.out.println("The number is odd");
// trying to figure out how to get the code to terminate if you put in a value
// that isn't a number
System.out.println("Type 1 to continue, 0 to terminate");
x = s.nextInt();
}
}
}

TA貢獻2012條經驗 獲得超12個贊
要在用戶輸入數字以外的任何內容時退出程序,請將變量 x 類型更改為字符串
if (!StringUtils.isNumeric(x)) {
System.exit(0);
}
當用戶輸入 2 時退出程序
if (x == 2) {
System.exit(0);
}
添加回答
舉報