我有这种方法,我试图从文本文件读入,然后将其中的内容添加到我的数组,我的方法似乎没问题,但是当我朗读程序时,我在屏幕上显示 null 请帮助我的代码。
File text = new File("C:\\Users\\Stephen\\Desktop\\CA2\\src\\Management_System_Package\\GAMES.txt");
Scanner scnr = new Scanner(text);
String GameLine;
GameLine = scnr.nextLine();
while (scnr.hasNextLine()) {
Management_System Game = new Management_System("", "", 0, 0, 0);
int Comma1 = GameLine.indexOf(", ");
String Title = GameLine.substring(0, Comma1).trim();
Game.setTitle(Title);
System.out.print(Title);
int Comma2 = GameLine.indexOf(", ", Comma1 + 1 );
String Genre = GameLine.substring(Comma1 + 1, Comma2);
Game.setGenre(Genre);
int Comma3 = GameLine.indexOf(", ", Comma2 + 1 );
String ID = GameLine.substring(Comma2 + 1, Comma3);
Game.setID(Double.parseDouble(ID));
int Comma4 = GameLine.indexOf(", ", Comma3 + 1 );
String Rating = GameLine.substring(Comma3 + 1, Comma4);
Game.setRating(Integer.parseInt(Rating));
String Quantity = GameLine.substring(Comma4 + 1).trim();
Game.setQuantity(Integer.parseInt(Quantity));
add(Game);
GameLine = in.nextLine();
答案 0 :(得分:1)
这是因为您的代码有一个错误,您从循环中读取一行,并且您将始终跳过文件的最后一行。如果您的文件只有一行,则scnr.hasNextLine()
将为false
,并且不会运行while循环。
我认为split()
是获取所需字符串和整数的更好方法。像这样的代码:
String GameLine;
while (scnr.hasNextLine()) {
GameLine = scnr.nextLine();
Management_System Game = new Management_System("", "", 0, 0, 0);
String[] tags = GameLine.split(",");
Game.setTitle(tags[0]);
Game.setGenre(tags[1]);
Game.setID(Double.parseDouble(tags[2]));
Game.setRating(Integer.parseInt(tags[3]));
Game.setQuantity(Integer.parseInt(tags[4]));
add(Game);
}