0

I'm getting a input mismatch error but I'm not sure why. It was working on a different computer but it seems to not be working on my laptop.At first I thought it might be my txt file but that was not the reason.

import java.io.*;
import java.util.*;
public class FindGrade {
public static final int NUM_SCORE_TYPES = 5;   

public static void main(String[] args) {
    Scanner scan = null;
    int[] quizArray = null;    
    int[] labArray = null;     
    int[] attendance = null; 
    int[] midterms = null; 
    int quizgrade =0;
    int labgrade=0;
    int attendance_1=0;
    int midterms_1 =0;
    String name;


    try {
        scan = new Scanner(new File("input.txt")); 
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return;
    }

    // each iteration is for single exam type (ie: Quizzes is the 1st one)
    for (int i = 0; i < NUM_SCORE_TYPES; i++) {

        name = scan.next(); 
        int numScores = scan.nextInt();
        int maxGrade = scan.nextInt();

        if (name.equals("Quizzes")) {
            quizArray = new int[numScores];
            readScores(quizArray, numScores, scan);


        }

        else if (name.equals("Labs")) {
            labArray = new int[numScores];
            readScores(labArray, numScores, scan);

        }
        else if (name.equals("Lab_attendance")) {
            attendance = new int[numScores];
            readScores(attendance, numScores, scan);

        }
        else if (name.equals("Midterms")) {
            midterms = new int[numScores];
            readScores(midterms, numScores, scan);

        }

    }

}


public static void readScores(int[] scoreArray, int numScores, Scanner scan) {
    for (int i = 0; i < numScores; i++) { 
        scoreArray[i] = scan.nextInt();
    }
}

public static void average(double [] scoreArray, int numScores){
    double sum=0;
    for(int i=0; i< scoreArray.length; i++){
        sum += scoreArray[i];
    }
    double average = sum/numScores;

    System.out.println(sum + " " + average);



}

}

output:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:840)
    at java.util.Scanner.next(Scanner.java:1461)
    at java.util.Scanner.nextInt(Scanner.java:2091)
    at java.util.Scanner.nextInt(Scanner.java:2050)
    at FindGrade.main(FindGrade.java:33)

input file:

Quizzes 8 10
5 8 9 10 4 0 10 7
Labs 6  100
95  90  100  87  63  92
Lab_attendance  16  1
1  1  1  0  1  1  1  1  0  1  1  1  1  0  1  1
Midterms  2  100
87  94
Final  0  100   
user124557
  • 11
  • 5

1 Answers1

0

Your code is working fine with the data that you posted. It will give this error if variable "name" will be assigned value different from 5 names that you are expecting, like "Quizze" instead of "Quizzes". In that case your code logic gets corrupted and you will have this error. This is one possible root cause.