Search code examples
javaexceptiontry-catchinputmismatchexception

InputMismatchException Handling in My Program? - JAVA


Sorry but I'm still very new to Java and I've tried to figure this out with online help. I am trying a try/catch to handle InputMismatchException after "Enter the homework grades for the students" (in case they enter a letter rather than number). It is not working out so far. What should the code look like to accomplish this?

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");
        }
}

}

I still get the InputMismatchError even when I try and catch around the code for the "Enter the homework grades for the students". I attempt inserting the try and catch to different spots and use different code within it but no luck.

EDIT: No guys, duplicate scanner is not my issue. I cannot successfully handle InputMismatchException and I've been trying to do so for several hours. Please help!


Solution

  • You can change your code with: Old code: hw[hw2]=scan.nextDouble();

    New code: hw[hw2]= Double.valueOf(scan.next().trim());