JAVA - 扫描程序 - 错误NoSuchElementException

时间:2015-09-21 20:55:50

标签: java java.util.scanner

我在运行此功能时遇到错误。它使用Scanner在某个文件中找到一个单词。

这是:

public static boolean VerifyExistWord(File FileToSearch, String WordToFind) {

    boolean result = false;
    try (Scanner ind = new Scanner(FileToSearch)) {
        while (ind.hasNextLine()) {
            String word = ind.next();
            if (word.equalsIgnoreCase(WordToFind)) {
                result = true;
            }
        }
    } catch (FileNotFoundException e) {
    }
    return result;
}

但是当我执行此操作时,我会遇到NoSuchElementException

  

线程中的异常" pool-1-thread-13777"   java.util.NoSuchElementException at   java.util.Scanner.throwFor(Scanner.java:907)at   java.util.Scanner.next(Scanner.java:1416)at   TP.FuncoesAuxiliares.VerifyExistWord(FuncoesAuxiliares.java:66)     在TP.PesquisaThreaded.run(PesquisaThreaded.java:90)at   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)     在   java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:615)     在java.lang.Thread.run(Thread.java:745)

有人可以帮助我吗?

感谢。

1 个答案:

答案 0 :(得分:2)

确保首先调用next()

if(ind.hasNext()) {
    String word = ind.next();
    ...
}