Search code examples
javajava.util.scannermismatch

Java NextBoolean() read from text file


Hey guys im getting these errors when trying to read from a text file:

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 application.Test.main(Test.java:27)

From trying to work out what the problem is I think its the nextBoolean() as when I remove this I dont get any errors.

Here's my code:

package application;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Scanner;

    public class Test {

        public static void main(String[] args) throws FileNotFoundException {
            // TODO Auto-generated method stub

            int age = 0;
            String type = null, name = null, breed = null, desc = null;
            boolean male = false;

            File file = new File("animals.txt");
            Scanner kb = new Scanner(file);

            while (kb.hasNext()) {

                age = kb.nextInt();
                kb.nextLine();
                type = kb.nextLine();
                male = kb.nextBoolean();
                name = kb.nextLine();
                breed = kb.nextLine();
                desc = kb.nextLine();

                Animal animal = new Animal(age, type, male, name, breed, desc);

                AnimalList.add(animal);

            }
            AnimalList.printAnimalList();
            kb.close();
        } 


    }

Here's the text file contents

6
Dog
false
Fred
Jack Rusell
dog is in poor condition
5
Cat
false
James
Russian blue
Good
9
Cat
true
Felix
Tabby
Cat in good condition
4
Bird
true
chirpy
Parrot
Parrot in good condition

I would be grateful for any help. I've been googling for the past few hours and I can't find any explanation.


Solution

  • You are missing a call to nextLine after nextBoolean.

    The nextBoolean and nextInt method won't read the lineFeed of your line, it will stop right away after reading the boolean or int.

    You retrieve the name directly by calling nextLine and you expect "Fred" but instead get an empty string because you are still on the same line. "Fred" will actually be assigned to breed and your reading is corrupted.