我的程序中的 InputMismatchException 处理? - JAVA

InputMismatchException Handling in My Program? - JAVA

抱歉,我对 Java 还是很陌生,我已经尝试通过在线帮助解决这个问题。我正在尝试 try/catch 在 "Enter the homework grades for the students" 之后处理 InputMismatchException(以防他们输入字母而不是数字)。到目前为止还没有解决。完成此操作的代码应该是什么样的?

package exceptionHandling;
import java.util.Scanner;
import java.util.InputMismatchException;

public class ExceptionHandling {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    double total=0;     
    System.out.println("Enter the number of homework assignments:");
    int homeworkGrades = scan.nextInt();
    double hw[]=new double[homeworkGrades];

    System.out.println("Enter the homework grades for the student:");
    for (int hw2=0;hw2<hw.length;hw2++){
        hw[hw2]=scan.nextDouble();
    }
        for(int i=0;i<hw.length;i++){
            total=total+hw[i];
        }   

    scan.close();
    double average=total/homeworkGrades;
    System.out.println("The average homework grade is "+average);
    if (average < 101 && average >= 90) {
        System.out.println("A");
    }
        else if (average < 90 && average >= 80) {
            System.out.println("B");
        }
            else if (average < 80 && average >= 70) {
                System.out.println("C");
            }
            else if (average < 70 && average >= 60) {
                System.out.println("D");
            }
            else if (average < 60) {
                System.out.println("F");
        }
}

}

即使我尝试捕获 "Enter the homework grades for the students" 的代码,我仍然会遇到 InputMismatchError。我尝试将 try and catch 插入到不同的位置并在其中使用不同的代码,但没有成功。

编辑:不,伙计们,重复扫描仪不是我的问题。我无法成功处理 InputMismatchException 并且我已经尝试这样做了几个小时。请帮忙!

如果您不想处理异常错误,可以使用.hasNextDouble()、.hasNextInt() 等来检查是否还有另一个double。

您可以更改代码: 旧代码:hw[hw2]=scan.nextDouble();

新代码:hw[hw2]= Double.valueOf(scan.next().trim());

我的建议是首先将输入扫描为 String 然后看看它是否可以表述为 intdouble:

String test = "1234.0";
if (test.matches("[0-9.]+")) {
    double val = Double.parseDouble(test);
    System.out.println(val);
} else {
    System.out.println("not found");
}

test.matches("[0-9.]+") returns true 如果字符串 test 仅包含数字和浮点数。因此,如果 test 中还有其他字符,matches() 将 return 变成 false.

"[0-9.]+"是正则表达式,不知道你的课程是否允许。如果不是,则可能需要遍历String字符,使用isDigit()进行判断。

在将正则表达式更改为 "[0-9]+" 后,同样可以应用于 int,也就是没有浮点数。那么:

int val = Integer.parseInt(test);