我不希望用戶輸入負值。我如何檢測負值和InputMismatchException
?這是迄今爲止的代碼!該代碼似乎並不正確,並且無法確定問題出在哪裏。我想驗證用戶輸入以確保負數,字符串和double無效,並提示用戶輸入正確的數字,該數字應該是正整數。驗證倍數輸入
do {
try {
System.out.println("How many " + teaName + " did you today?");
if(input.hasNextInt() && (numberItem = input.nextInt()) > 0) {
istrue = false;
numberItem = input.nextInt();
}
} catch (InputMismatchException e) {
input.nextLine();
System.out.println("Please enter right number");
istrue = true;
}
catch (NoSuchElementException e){
System.out.println(" Please enter positive integers");
}
} while (istrue);
負數不是'Scanner'拋出的異常,所以你不能將它添加到'catch'塊 – Idos
你能發佈你的整個代碼嗎? –