Search code examples
javaarraylistimportinputmismatchexception

InputMismatchException while inputting multiple lines into ArrayList


While putting a .txt file into a list I keep running into a InputMismatchException error. That won't read the "MovieType" or "AlbumTitle". Relevant code has been added.

public class MovieManager {

    public static void main(String[] args) throws FileNotFoundException {
        ArrayList<MediaItem> list = new ArrayList<>();
        Scanner inputFile = new Scanner(new File("collection.txt"));
        try {
            while (inputFile.hasNextLine()){
                String mediaType = inputFile.nextLine();
                if (mediaType.equals("Movie")){
                    String movieTitle = inputFile.nextLine();
                    //System.out.println("String" + movieTitle);
                    int movieYear = inputFile.nextInt();
                    //System.out.println("int" + movieYear);
                    String movieType = inputFile.nextLine();
                    //System.out.println("String" + movieType);
                    Movie mov = new Movie(movieTitle, movieYear, movieType);
                    list.add(mov);
                } else if (mediaType.equals("Album")) {
                    String albumArtist = inputFile.nextLine();
                    //System.out.println("String" + albumArtist);
                    int albumYear = inputFile.nextInt();
                    //System.out.println("int" + albumYear);
                    String albumTitle = inputFile.nextLine();
                    //System.out.println("String" + albumTitle);
                    Album alb = new Album(albumArtist, albumYear, albumTitle);
                    list.add(alb);
               }
            }
            inputFile.close();
            System.out.print(list);
        } catch(InputMismatchException e) {
           inputFile.next();
        }
    }
}

Collection.txt

Album
ABBA
1976
Arrival
Album
ABBA
1981 
The Visitors
Album
The Beatles
1969
Abbey Road
Album
Nazareth
1975
Hair of the Dog
Movie
Beauty and the Beast
1991
VHS
Movie
It's a Wonderful Life
1946
DVD
Movie
Tron
1983
Laserdisc
Movie
Tron: Legacy
2010
Blu-ray

Solution

  • With an input stream containing 1976\n, a call to Scanner#nextInt() will consume only the digit characters. It leaves the \n newline character in the input stream, for the next call to a Scanner method to deal with.

    The subsequent call to Scanner#nextLine() immediately sees the \n, character, and consumes it, and returns the empty string, because after the digits 1976 to the end of the line was the empty string.

    Or, visualized another way... nextLine(), nextInt(), nextLine() parses:

    ABBA \n 1976 \n Arrival \n
    

    as:

    [ABBA\n][1976][\n]
    

    returning:

    "ABBA"   1976  ""
    

    Solution:

    You need to discard the remainder of the "year" line, after calling nextInt(), by immediately calling nextLine(), and ignoring the returned value.