为什么我从正在读取的文件中将更多行添加到阵列列表中?

时间:2019-05-26 06:21:54

标签: java

该文件仅包含4行,当我在for循环中添加nextLine()时,出现错误“线程“主”中的异常” java.util.NoSuchElementException:未找到任何行”,但是如果我把它放在for循环之前,或者如果我在for循环之前添加,它将存储8个类。

在for循环之前和之后以及在其中循环移动nextLine,并更改for循环中的x等于

public static void main(String args[]) {
        WLS client = new WLS();
        print("WLS Status: " + client.status());
        client.checkFileSize();
        print("Login Lines: " + loginLines);
        client.getLogins();
        print("Logins Stored: " + loginList.size());
    }

public void getLogins() {
            String[] parsedLogin;
            if(active) {
                try {
                    print("Gathering info from file: " + inputFile + ".txt");
                    file = new Scanner(new File(inputFile + ".txt"));
                    while(file.hasNextLine()) {
                        parsedLogin = file.nextLine().split(" ");
                        file.nextLine();
                        for(int x = 0; x < logins.length; x++) {
                            logins[x] = new Logins(parsedLogin[0], parsedLogin[1], parsedLogin[2]);
                            loginList.add(logins[x]);//#TODO Storing 8 for some reason file.nextLine(); is causing a breakage NEED TO FIX!!
                            file.nextLine();
                        }
                    }
                } catch(FileNotFoundException e) { print("File not found"); }
            } else { print("Activate WLS to proceed"); }
        }

我希望输出为:

WLS Activated
WLS Status: true
Enter database name: (Do NOT include extension! i.e. '.txt')
database
Login Lines: 4
Gathering info from file: database.txt
Logins Stored: 4

但是实际输出是:

WLS Activated
WLS Status: true
Enter database name: (Do NOT include extension! i.e. '.txt')
database
Login Lines: 4
Gathering info from file: database.txt
Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at Main$WLS.getLogins(Main.java:59)
    at Main.main(Main.java:17)

1 个答案:

答案 0 :(得分:1)

您将下一行的读数放置在错误的循环内。 您有两个循环:第一个读取行,第二个在分割行上。 第一个循环确定读取行的顺序

file = new Scanner(new File(inputFile + ".txt"));
while(file.hasNextLine()) {
    parsedLogin = file.nextLine().split(" ");  // only place to read line
    for(int x = 0; x < logins.length; x++) {
        logins[x] = new Logins(parsedLogin[0], parsedLogin[1], parsedLogin[2]);
        loginList.add(logins[x]);//#TODO Storing 8 for some reason file.nextLine(); is causing a breakage NEED TO FIX!!
    }
}