因此,我创建了程序的一部分,应该从文本文件中读取它。问题是它只能(无瑕疵地)读取前两行,而第二次循环时,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 - Java,扫描程序仅读取前两行,而忽略其余两行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58343823/

10-14 01:56