gpt4 book ai didi

Java,Scanner只读取前两行,忽略其余的

转载 作者:行者123 更新时间:2023-12-01 23:17:27 26 4
gpt4 key购买 nike

所以我创建了程序的一部分,它应该从文本文件中读取。问题是它只读取前两行(完美地),并且当它第二次循环时 tempLine 是“”。因此我得到了 ArrayIndexOutOfBoundsException。为什么会发生这种情况?

每个人有 2 行。这些已添加到列表中。

文件如下所示:

7603021234, Alhambra Aromes
2018-07-01
8104021234, Bear Belle
2018-12-02
8512021234, Chamade Coriola
2017-03-12
7608021234, Diamanda Djedi
2019-01-30
7605021234, Elmer Ekorrsson
2010-04-07
7911061234, Fritjoff Flacon
1999-12-16
1111111111, Greger Ganache
2019-03-23
5711121234, Hilmer Heur
2019-08-18
2222222222, Ida Idylle
2017-03-07
1212121212, Jicky Juul
2018-09-27
4604151234, Kadine Karlsson
2018-01-09
9110261234, Liu Lingren
2018-02-15
7907281234, Mitsuko Mayotte
2018-12-22
7805211234, Nahema Ninsson
2019-01-04

这是我的源代码:

   public class ReadFile {

private List<Customer> allMembers = new LinkedList<>();

public void readFile () throws IOException {

String tempLine;
String[] tempString;
String personalNumber;
String firstName;
String lastName;
LocalDate lastPayed;

Path inFilePath = Paths.get("C:\\Users\\Allan\\Documents\\Nackademin\\OOP\\Inlämningsuppgift2\\customers.txt");
Scanner fileScanner = new Scanner(inFilePath);

while(fileScanner.hasNext()) {
tempLine = fileScanner.nextLine();
tempString = tempLine.split(" ");
personalNumber = tempString[0].replace(",", "");
firstName = tempString[1];
lastName = tempString[2];

if (fileScanner.hasNext()) {
lastPayed = LocalDate.parse(fileScanner.next());
allMembers.add(new Customer(personalNumber, firstName, lastName, lastPayed));
}

}
}

public List<Customer> getAllMembers() {
return allMembers;
}
}

最佳答案

请在 next() 上使用 nextLine()。

while(fileScanner.hasNextLine()) {
tempLine = fileScanner.nextLine();
tempString = tempLine.split(" ");
personalNumber = tempString[0].replace(",", "");
firstName = tempString[1];
lastName = tempString[2];

if (fileScanner.hasNextLine()) {
lastPayed = LocalDate.parse(fileScanner.nextLine());
allMembers.add(new Customer(personalNumber, firstName, lastName, lastPayed));
}

}

关于Java,Scanner只读取前两行,忽略其余的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58343823/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com