benglennlop
benglennlop

Reputation: 23

How do I fix an InputMismatchException error that comes from scanner incorrectly reading a file?

I am trying to simply read the first thing in a file and set a variable to hold that value. The first line of the file is 10 (see below) and I am using .nextInt() to try to read the value but I am getting this error message:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at project5.Project5.readPlayers(Project5.java:39)
at project5.Project5.main(Project5.java:19)

Here is the relevant code:

private static Player[] readPlayers( String fileName ) {
    String name = "", catchPhrase = "";
    int age = 0, count = 0;

    //set up to read the file
    Scanner inStream = new Scanner(fileName);

    //read the first line
    int numPlayers = inStream.nextInt();
    inStream.nextLine();

    //create arrays, one to hold all the possible players and one to hold if they are old enough
    Player[] allPlayers = new Player[numPlayers];
    boolean[] oldEnough = new boolean[numPlayers];

Here is the file:

10
Rincewind 28 Luggage! 
MoistVonLipwig 30 Postal!
CaptainCarrotIronfoundersson 20 I am a 6'6 dwarf
GrannyWeatherwax 88 I ate'nt dead!
Eskarina 22 8th! 
Tiffany 19 Cheese! 
Vetinari 52 Si non confectus, non reficiat 
Igor 180 What goeth around, cometh around... or thtopth 
NobbyNobbs 17 tis a lie sir, i never done it 
DaftWullie 45 Aye, Criverns! 

All I am trying to do is read the 10 and move to the next line with my code.

Upvotes: 2

Views: 260

Answers (1)

MasterOdin
MasterOdin

Reputation: 7896

It's because you're passing in a string (that contains the filename) to Scanner which it interprets literally. So if fileName = "test.txt", all your scanner contains is "test.txt" (and not the contents of the file). So when you do scanner.nextInt(), it throws an exception as there is no next ints to be found (you'd only be able to scanner.next() to get the fileName back). However, what you want to do is pass in a file handler (using File) into Scanner, which'll then read the contents of the file into the stream which you can then manipulate like you're trying to.

What you want to do is:

try {
    File file = new File(fileName);
}
catch (FileNotFoundException e) {
    e.printStackTrace();
}
Scanner inStream = new Scanner(file);

This'll read in the file contents into the Scanner allowing you do do what you're expecting. (Note: File comes from java.io.File)

Upvotes: 2

Related Questions