3 回答

TA貢獻1801條經驗 獲得超8個贊
測試是否是int一個異常,如果不是則拋出異常
a=sc.nextLine();
Integer.valueOf(a); // throws NumberFormatException
// this is number so go to top of loop
continue;
} catch(NumberFormatException b) {
System.out.println("There is NO problem with your input");
// we can use `a` out side the loop
}

TA貢獻1815條經驗 獲得超13個贊
使用該技術嘗試解析用戶作為 int 輸入的內容。如果轉換成功,這意味著他們輸入了一個整數,你應該拋出一個異常,因為你說你不希望他們輸入一個整數(我理解這意味著你不希望他們只輸入一個數字序列)
我沒有給你確切的答案/為你編寫代碼,因為你顯然在學習 Java,這是一個學術練習。你的大學/學校對教授/評估我的編程能力不感興趣,他們對你的感興趣,所以我為你做你的工作對你沒有任何價值:)
如果您在實施我的建議時遇到困難,請編輯您的問題以包含您改進的代碼,我們可以再次提供幫助
作為旁注,我建議您將錯誤消息做得更好,以“出現問題”對用戶來說,沒有什么比被告知存在問題但不知道問題是什么或如何解決更令人沮喪的了。

TA貢獻1866條經驗 獲得超5個贊
使用正則表達式可以最好地解決此問題,但由于您的要求是使用 try catch,因此您可以使用以下方法
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = null;
System.out.println("\n\nEnter the name");
try {
// try to get Integer if it is number print invalid input(because we
// don't want number)
sc.nextInt();
System.out.println("There is problem with your input");
}
//getting exception means input was not an integer
// if input was not an Integer then try to read that as string and print
// the name
catch (InputMismatchException b) {
a = sc.next();
System.out.println("You name is " + a);
}
}
添加回答
舉報