我正在编写一个使用Scanner类的程序,并希望使用try-catch块来捕获InputMismatchExceptions。这就是我写的:
public class StudentInfo{
public static void main(String[] args){
Scanner scnr = new Scanner(System.in);
int creditHours = 0;
try
{
System.out.println("Please enter the number of credit hours that you currently have (do not count credit hours from classes that you are currently attending this semester)");
creditHours = scnr.nextInt();
}
catch(InputMismatchException e){
System.out.println("CLASSIFICATION ERROR: NUMBER NOT RECOGNIZED. ENTER AN INTEGER FOR CREDIT HOURS");
Scanner input = new Scanner(System.in);
creditHours = input.nextInt();
}
String studentClass = checkStudent (creditHours);
System.out.println("Official Student Classification: " + studentClass);
}
try-catch块工作一次,如果我第一次放入24.5,它会捕获异常并让用户重新键入他们拥有的信用小时数但是如果他们重新键入非第二次整数,它无法再次捕获错误并发出相应的消息。基本上,我想知道是否有任何方式可以继续捕获异常并发送错误消息,无论他们尝试多少次。我尝试过使用do-while循环或while语句,但它不起作用,所以是的。另外,我在catch块中创建了一个新的scanner变量,因为如果没有,它不允许我在出于某种原因给出错误消息后输入一个新的整数。它实际上将抛出我键入的错误,然后继续给我Java的InputMismatchException错误。
以下是我尝试使用while循环的方法:
int creditHours = 0;
while(creditHours <= 0){
try
{
System.out.println("Please enter the number of credit hours that you currently have (do not count credit hours from classes that you are currently attending this semester)");
creditHours = scnr.nextInt();
}
catch(InputMismatchException e){
System.out.println("CLASSIFICATION ERROR: NUMBER NOT RECOGNIZED. ENTER AN INTEGER FOR CREDIT HOURS");
Scanner input = new Scanner(System.in);
creditHours = input.nextInt();
}
}
String studentClass = checkStudent (creditHours);
System.out.println("Official Student Classification: " + studentClass);
}
答案 0 :(得分:0)
您需要将try-catch置于循环中才能重新运行代码。
试试这个:
public class StudentInfo{
public static void main(String[] args){
int creditHours = 0;
boolean ok = false;
System.out.println("Please enter the number of credit hours that you currently have (do not count credit hours from classes that you are currently attending this semester)");
while (!ok)
{
try
{
Scanner scnr = new Scanner(System.in);
creditHours = scnr.nextInt();
ok = true;
}
catch(InputMismatchException e){
System.out.println("CLASSIFICATION ERROR: NUMBER NOT RECOGNIZED. ENTER AN INTEGER FOR CREDIT HOURS");
}
}
String studentClass = checkStudent (creditHours);
System.out.println("Official Student Classification: " + studentClass);
}