0

I am trying to read a serise of variables from a text file with this code:

public static Book readBook(String pathname) throws IOException, InputMismatchException {
        Scanner fl = new Scanner (new FileInputStream (fn));
        int num = fl.nextInt();
        double thePrice = 0;
        String theAuthor = null;
        String theTitle = null;
        for (int i=0; i<=num; i++) {
            theTitle = fl.nextLine();
            theAuthor = fl.nextLine();
            thePrice = fl.nextDouble();
        }
        System.out.print(num);
        System.out.print(theTitle);
        System.out.print(theAuthor);
        fl.close();
        return new Book(theTitle, theAuthor, thePrice);
       }

The File contains a number that is used in the while loop to state how many passes are needed. The File looks like this:

2
name
author
10.00
name2
author2
12.00

But this throws an input mismatch error that for some reason reads the first line as 'name2' messing up the order and causing the error when the code reaches the double. Any Help would be appreciated!

Stack Trace:

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.nextDouble(Unknown Source)
    at Model.readBook(Model.java:36)
Kamon241
  • 65
  • 3
  • 11
  • 4
    Exactly this issue has come and been asked may be 100 times on SO only. Did you try to even google it with the name of your exception? – Rohit Jain Feb 20 '13 at 18:51
  • Whatever is the solution in that question, same applies here to `nextDouble()`. – Rohit Jain Feb 20 '13 at 18:55

1 Answers1

1

When you call fl.nextInt() or fl.nextDouble(), the following call to fl.nextLine() doesn't actually read the "next line". Instead, it just finishes reading the remaining "characters" (or "line separator") on the line that contains the int or double values. So you need to throw in an extra fl.readLine() at the beginning of your for loop, in this specific scenario.

Also, you're going to want to say "i<num" instead of "i<=num" or else you're going to get a different error.

In essence, make the start and first line of your for loop as such:

 for (int i=0; i<num; i++) {
    fl.nextLine();
.....
.....
Jason McKim
  • 111
  • 1