簡體   English   中英

Java Scanner hasNextLine NoSuchElementException?

[英]Java Scanner hasNextLine NoSuchElementException?

我試圖逐行讀取一個大的csv文件,以便找到其中的字符串出現次數。

這是執行它的代碼:

public int getOffset(File file, String searched) throws FileNotFoundException {
    Scanner scanner = new Scanner(file).useDelimiter(System.getProperty("line.separator"));
    int occurences = 0;
    while (scanner.hasNextLine()) {
        String s = scanner.next();
        if (s.indexOf(searched) >= 0) {
            occurences++;
        }
    }
    return occurences;
}

但是,在讀取文件的最后一行后,它再次檢查while條件,並退出此異常:

java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at fr.sgcib.cva.mat.MatWriter.getOffset(MatWriter.java:83)
at fr.sgcib.cva.mat.MatWriter.writeFooter(MatWriter.java:71)
at fr.sgcib.cva.mat.NettingNodeHierarchyExtract.getLeNodes(NettingNodeHierarchyExtract.java:65)
at fr.sgcib.cva.mat.Mat.main(Mat.java:55)

為什么不檢測它是文件的結尾?

使用String s = scanner.nextLine(); 而不是String s = scanner.next();

這意味着您的代碼將如下所示:

public int getOffset(File file, String searched) throws FileNotFoundException {
    Scanner scanner = new Scanner(file).useDelimiter(System.getProperty("line.separator"));
    int occurences = 0;
    while (scanner.hasNextLine()) {
        String s = scanner.nextLine();
        if (s.indexOf(searched) >= 0) {
            occurences++;
        }
    }
    return occurences;
}

通常,在使用Scanner你的has...條件需要匹配next...數據檢索方法

您正在檢查下一行是否存在並掃描下一個單詞。 將while到while(scanner.hasNext())或掃描行中的條件更改為String s = scanner.nextLine()

嘗試這個:

public int getOffset(File file, String searched) throws FileNotFoundException {
    Scanner scanner = new Scanner(file).useDelimiter(System.getProperty("line.separator"));
    int occurences = 0;
    while (scanner.hasNext()) {
        String s = scanner.next();
        if (s.indexOf(searched) >= 0) {
            occurences++;
        }
    }
    return occurences;
}

要么

public int getOffset(File file, String searched) throws FileNotFoundException {
    Scanner scanner = new Scanner(file).useDelimiter(System.getProperty("line.separator"));
    int occurences = 0;
    while (scanner.hasNextLine()) {
        String s = scanner.nextLine();
        if (s.indexOf(searched) >= 0) {
            occurences++;
        }
    }
    return occurences;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM