抱歉,我对 Java 还很陌生,我尝试通过在线帮助来解决这个问题。我正在尝试尝试/捕获来处理“输入学生的作业成绩”之后的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");
}
}
}
即使当我 try catch “输入学生的作业成绩”的代码时,我仍然会遇到InputMismatchError。我尝试将 try 和 catch 插入到不同的位置并在其中使用不同的代码,但没有成功。
编辑:不,重复扫描仪不是我的问题。我无法成功处理 InputMismatchException,并且我已经尝试这样做了几个小时。请帮忙!
最佳答案
如果您不想处理异常错误,可以使用 .hasNextDouble()、.hasNextInt() 等来检查是否存在另一个 double。
关于java - 我的程序中的 InputMismatchException 处理? - JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57650131/