我正在嘗試檢查用戶是否輸入了字串。如果用戶輸入一個字串,我的程式應該輸出一個錯誤資訊。如果用戶輸入一個整數,我的程式應該繼續執行該程式
到目前為止,這是我的代碼,我需要添加另一個條件來檢查用戶是否輸入字串,我嘗試了一些方法但它們不起作用
public int UserInput() {
boolean Continueasking = true;
int Input = 0;
while (Continueasking) {
Input = io.nextInt();
if (Input == 1 || Input==2 || Input==3) {
Continueasking = !Continueasking;
} else {
System.out.println("try again");
}
}
return Input;
uj5u.com熱心網友回復:
nextInt()將用戶輸入決議為整數。如果用戶輸入無法決議為整數,則拋出InputMismatchException. 您可以捕獲此例外并按照您認為合適的方式處理它。
while (continueAsking) {
try {
input = io.nextInt();
} catch (InputMismatchException ex) {
// invalid input - handle exception
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/457663.html
下一篇:如果陣列為空,則向用戶列印訊息
