谁能解释为什么我的 try/catch 不起作用?我试图做到这一点,如果用户输入一个字母,它将收到错误消息,或者如果他们输入的数字不在我的选项中,他们也会收到错误消息。我似乎得到的只是输入字母时常见的红线错误,如果我输入例如数字 6,则没有任何反应。
public void menu()
{
System.out.println("Welcome to your Payroll System");
System.out.println();
System.out.println("Please enter your choice below from the following options");
System.out.println();
System.out.println("View all current weekly employees = 1 ");
System.out.println("View all current monthly employees = 2 ");
System.out.println("Delete an employee = 3 ");
System.out.println("Add an employee = 4 ");
System.out.println("Print an employee payslip = 5");
System.out.println("To exit the system = 0 ");
// allows user to enter number of choice and this reflects which statement is ran in userChoice method
tempvar = sc.nextInt();
userChoice();
}
public void userChoice()
{
try
{
// if user enters 1 it prints out the employee list.
if (tempvar == 1)
{
w.printWeekly();
}
if (tempvar == 2)
{
mo.printMonthly();
}
if (tempvar == 3)
{
e.deleteEmployee();
}
if (tempvar == 4)
{
e.addEmployee();
}
if (tempvar == 5)
{
mo.createPayslip();
}
if (tempvar == 0) // if user hits 0 it allows them to exit the programme
{
System.out.println("You have exited the system");
System.exit(0);
}
}
catch(InputMismatchException e)
{
System.out.println("Error in the data you have entered please try again");
}
catch(Exception e)
{
System.out.println("Error in the data you have entered please try again");
}
}
}