JavaArrayList缺少第一个值
我正在从文本文件中获取数据并将其放入 ArrayList。然而,文本文件的第一行没有被打印出来。
public static void secondMain() {
BufferedReader reader;
var lines = new ArrayList<String>();
var rooms = new ArrayList<Room>();
try {
reader = new BufferedReader(new FileReader("rooms.txt"));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
lines.add(line);
}
reader.close();
for (int i = 0; i < lines.size() - 1; i++) {
String[] words = lines.get(i).split(" ");
var room = new Room();
room.RoomNumber = Integer.parseInt(words[0]);
room.Type = (words[1]);
room.Price = Double.parseDouble(words[2]);
room.Bool1 = Boolean.parseBoolean(words[3]);
room.Bool2 = Boolean.parseBoolean(words[4]);
room.Availability = (words[5]);
rooms.add(room);
}
for(int i = 0; i < rooms.size(); i++) {
System.out.println(rooms.get(i).RoomNumber);
System.out.println(rooms.get(i).Type);
System.out.println(rooms.get(i).Price);
System.out.println(rooms.get(i).Bool1);
System.out.println(rooms.get(i).Bool2);
System.out.println(rooms.get(i).Availability);
}
为图像道歉,这是我弄清楚如何显示文本文件格式的唯一方法。
当前输出显示房间号 102 作为第一个房间,这显然是不正确的。
如果有人也可以帮助我弄清楚如何以与文本文件相同的方式格式化我的控制台输出,那也很棒。目前它在不同的行上显示每个单独的字符串/整数等。
谢谢。
如果您需要更多信息,请询问!
回答
这与ArrayList. 您可以通过将lines.add(line)调用替换为 来重现该问题,System.out.println(line)并且您会看到输出中缺少第一行。在readLine()while 循环之前查看您对,的第一次调用。您测试该值是否为非空......这就是您对它所做的一切(我的评论):
String line = reader.readLine(); // Read the value...
while (line != null) { // Test for it being non-null
line = reader.readLine(); // Then ignore the value you've just tested,
// by reading the next line.
lines.add(line);
}
然后你再打电话readLine()。请注意,您的列表将始终以一个null值结尾(除非它是读取的第一行),因为您的循环有效地表示“而我添加到列表中的最后一个条目不为空”。最简单的解决方法是交换循环中语句的顺序:
String line = reader.readLine();
while (line != null) {
lines.add(line);
line = reader.readLine();
}
现在,在阅读下一行之前,您将在检查它是否为 non-null 之后立即添加一行。