简体   繁体   中英

java.util.InputMismatchException error when scanning from a .txt file

I am creating a program where 2 classes are used. In one class, i create methods that are then called by the second class. All methods are contained in the first class and the 2nd class simply calls them and executes the code.

Class 1

 import java.io.File;
 import java.io.FileNotFoundException;
 import java.util.Scanner;


 public class Student {


    private Scanner scanner;
    private String firstName;
    private String lastName;
    private int homeworkScore;
    private int testScore;
    private String letterGrade;
    private int numberOfStudents;

    public Student () {

        String firstName = null;
        String lastName = null;
        int homeworkScore = 0;
        int testScore = 0;
        String letterGrade = null;
        int numberOfStudents = 0;
    }


    public void openFile(){
        try { 
            scanner = new Scanner(new File("grades.txt"));
        } catch (FileNotFoundException e) { 
            System.out.println("Error opening file. Please make sure that you have a grades.txt file in the same folder as GradeCalculator.class");
            System.exit(0); 
        }
    }


    public void setNumberOfStudents() {
        System.out.println("It kinda works");
        numberOfStudents = scanner.nextInt();
    }

 public void setFastName() {
        fastName = scanner.next();
    }

 public void setLastName() {
        lastName = scanner.next();
    }

public void setHomeworkScore() {

        int subAssignment = 0;
        int assignment = 0;

        for(int i = 1; i <= 21; i++) { 
            subAssignment = scanner.nextInt();
            assignment += subAssignment;
        }

        homeworkScore = assignment;
    }

Class 2

  import java.io.File;
  import java.io.FileNotFoundException;
  import java.util.Scanner;


 public class CourseGrade {

public static void main(String[] args) {

    Student myStudent = new Student();

    myStudent.openFile();

    myStudent.setNumberOfStudents();

    myStudent.setFirstName();

    myStudent.setLastName();

    myStudent.setHomeworkScore();


}

 }

This is the error I get:

 It kinda works
 Exception in thread "main" java.util.InputMismatchException
 at java.util.Scanner.throwFor(Unknown Source)
 at java.util.Scanner.next(Unknown Source)
 at java.util.Scanner.nextInt(Unknown Source)
 at java.util.Scanner.nextInt(Unknown Source)
 at Student.setHomeworkScore(Student.java:54)
 at CourseGrade.main(CourseGrade.java:20)

...the "It kinda works" statement is just to see if it was calling the method correctly, which it looks like it is.

To my understanding, the error is telling me that it is reading the wrong type from the .txt file, but idk why that would be. Is it even reading the file correctly? Any type of help would be great, as I have been staring and messing with this code for hours!

According to the oracle java documentation, that exception is thrown, when the token doesn't fit the requested pattern (int) or is out of range .

If there's no more int in your file, that exception is thrown.
You could avoid that exception by checking if there's another int value to read with Scanners method hasNextInt .

For example:

for(int i = 1; i <= 21 && scanner.hasNextInt(); i++) { 
            subAssignment = scanner.nextInt();
            assignment += subAssignment;
}

(if that doesn't solve your problem, you should also include your input file)

Based on the error message, and where the error occurs, most likely you are trying to read an integer, but the actual data that you are reading is not a number.

You could verify this by changing your scanner.nextInt() to a scanner.next() and printing out the value that you actually get. Alternatively, you could add “error handling” of the form:

    for(int i = 1; i <= 21; i++) { 
        if (scanner.hasNextInt()
          subAssignment = scanner.nextInt();
        else
          throw new RuntimeException("Unexpected token, wanted a number, but got: " + scanner.next());
        assignment += subAssignment;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM