我是 Java 的初学者,正在尝试捕获异常“InputMismatchException”。以下是我的代码,希望它易于阅读,如果格式不正确,请提前道歉。它构建良好并执行,但是如果我输入一个字符,例如“catch”不起作用并且出现错误;
“线程“主”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");
}
}
}