![](/img/trans.png)
[英]java try/catch problems I want to catch ints entered in a string option
[英]Why is my try catch method not showing the error message I wrote for an entered String instead of integer? (Java)
System.out.println(" ");
System.out.println("Stage 4: Enter an integer between 5 and 500:");
IntEntry = keyedInput.nextInt();
if(IntEntry > 5 && IntEntry < 500)
{
System.out.println("You will go to stage 5.");
}
else
{
try
{
while(IntEntry < 5 || IntEntry > 500)
{
System.out.println("Try Again. Enter an integer that is between 5 and 500 characters long. “z”.");
IntEntry = keyedInput.nextInt();
}
}
catch(NumberFormatException e)
{
System.out.println("Try Again. Enter an integer between 5 and 500:.");
}
}
在上面的代碼中,我試圖獲取用戶在 5 到 500 之間輸入的有效 integer。如果用戶輸入的是字符串而不是integer ,程序應該使用try-catch方法向用戶發送一條消息 output。 try-catch方法對我不起作用,它會輸出一條錯誤消息。 有人能告訴我為什么try-catch方法在我的代碼中不起作用嗎?
Scanner 的nextInt
方法的 javadoc聲明它拋出InputMismatchException
。 不是NumberFormatException
。 (您對Integer.parseInt
感到困惑)。
像這樣更新你的代碼
System.out.println(" ");
System.out.println("Stage 4: Enter an integer between 5 and 500:");
try{
IntEntry = keyedInput.nextInt();
if(IntEntry > 5 && IntEntry < 500)
{
System.out.println("You will go to stage 5.");
}
else
{
try
{
while(IntEntry < 5 || IntEntry > 500)
{
System.out.println("Try Again. Enter a string that is between 5 and 15 characters long, and does not contain the letter “z”.");
IntEntry = keyedInput.nextInt();
}
}catch(NumberFormatException e)
{
System.out.println("Try Again. Enter a string that is between 5 and 15 characters long, and does not contain the letter “z”.");
}
}
}catch(NumberFormatException e)
{
System.out.println("Try Again. Enter a string that is between 5 and 15 characters long, and does not contain the letter “z”.");
}
使用Scanner#nextInt()
時,您應該捕獲InputMismatchException
而不是NumberFormatException
。 此外,您第一次使用nextInt()
不在try-catch塊內。 此外,當您稍后捕獲異常時,您的代碼不再循環。 您可以使用一個do-while循環和一個標志(例如valid
)來干凈地執行此操作。 只有當 integer 可以被解析並且在范圍內時,才會設置標志。 因此,循環繼續,直到用戶輸入范圍內的有效 integer。 這是一個完整的例子:
Scanner scanner = new Scanner(System.in);
System.out.println("Stage 4: Enter an integer between 5 and 500:");
int intEntry;
boolean valid = false;
do {
try {
intEntry = scanner.nextInt();
if (intEntry > 5 && intEntry < 500) {
valid = true; // set flag to leave loop
} else {
System.out.println("Integer out of range. Try Again. Enter an integer between 5 and 500:");
}
} catch (InputMismatchException e) {
System.out.println("Could not parse integer. Try again. Enter an integer between 5 and 500:");
scanner.next(); // clear invalid token
}
} while (!valid);
System.out.println("You will go to stage 5.");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.