将多行输入 ArrayList 时出现 InputMismatchException

InputMismatchException while inputting multiple lines into ArrayList

在将 .txt 文件放入列表时,我将 运行 置于 InputMismatchException 错误中。那不会读取 "MovieType" 或 "AlbumTitle"。已添加相关代码。

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

对于包含 1976\n 的输入流,对 Scanner#nextInt() 的调用将仅消耗数字字符。它在输入流中留下 \n 换行符,供下次调用 Scanner 方法处理。

随后调用 Scanner#nextLine() 立即看到 \n 字符,并使用它,returns 空字符串,因为在数字 1976 之后该行的末尾是空字符串。

或者,以另一种方式可视化... nextLine()、nextInt()、nextLine() 解析:

ABBA \n 1976 \n Arrival \n

如:

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

返回:

"ABBA"   1976  ""

解决方案:

您需要在调用 nextInt() 后丢弃 "year" 行的剩余部分,方法是立即调用 nextLine(),并忽略返回值。