将.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
答案 0 :(得分:0)
如果输入流包含1976\n
,则对Scanner#nextInt()
的调用只会消耗数字字符。它会在输入流中保留\n
换行符,以便下次调用Scanner
方法进行处理。
对Scanner#nextLine()
的后续调用会立即看到\n
,并使用它,并返回空字符串,因为在行的末尾的数字1976
之后是空字符串。
或者,以另一种方式可视化... nextLine(),nextInt(),nextLine()解析:
ABBA \n 1976 \n Arrival \n
为:
[ABBA\n][1976][\n]
返回:
"ABBA" 1976 ""
解决方案:
你需要丢弃&#34;年份的剩余部分&#34;在调用
nextInt()
之后,立即调用nextLine()
,并忽略返回的值。