我是一名Java初學者,並試圖捕獲異常'InputMismatchException'。以下是我的代碼,我希望它很容易閱讀,如果格式不正確,請提前致歉。它建立良好並且執行,但是如果我輸入一個字符,例如'catch'不起作用並且出現錯誤;(Java)無法捕捉異常
「異常線程‘main’java.util.InputMismatchException」
我相信一切的代碼工作正常包括「嘗試」了,我沒有什麼比一個其他漁獲會System.out.print命令。
import java.util.*; // imports
public class w4q1
{
public static void main(String[] args)
{
Scanner user_input = new Scanner(System.in); // declaring Scanner util
System.out.print("Please enter an integer: \n"); // Asks for input
int d = user_input.nextInt();
while (d > 0 || d < 0) // start of while loop, in the event of anything other than zero entered
{
try {
if (d < 0) // if statements
{
System.out.print("The integer " + d + " is negative\n");
break;
}
else if (d > 0)
{
System.out.print("The integer " + d + " is positive\n");
break;
}
else
{
System.out.print("You have not entered an integer\n");
break;
}
}
catch (InputMismatchException e) // Error message for letters/characters and decimals
{
System.out.print("You have entered an incorrect value, please restart the program\n");
}
}
if (d == 0)
{
System.out.print("A zero has been entered\n");
}
}
}
'int d = user_input.nextInt();'應該在'try'塊內。 –