java.util.NoSuchElementException: Read words from a file

我只是一个虾纸丫 提交于 2019-12-11 18:35:06

问题


what`s wrong with this simple java program?

I am trying to read words from a file and get the following exception:

complication
dilemma
lavender
issue
happy
weird
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1416)
    at com.recrawl.util.ReadWordsTextfile.readWordsFromTextFile(ReadWordsTextfile.java:32)
    at com.recrawl.util.ReadWordsTextfile.main(ReadWordsTextfile.java:13)

As you can see I get the words however, I also get an exception. I am using the following code:

public static void main(String[] args) {
    String path = "Word_and_phrases";
    ReadWordsTextfile r = new ReadWordsTextfile();
    r.readWordsFromTextFile(path);  
}

public ArrayList<String> readWordsFromTextFile(String path) {
    ArrayList<String> resultList = new ArrayList<String>();

    FileInputStream fileIn = null;
    try {
        fileIn = new FileInputStream(path);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Scanner scan = new Scanner(fileIn);
    while(scan.hasNextLine()) {
        String word = scan.next();
        word = word.replace(",", "");
        System.out.println(word);
        resultList.add(word);
    }
    scan.close();
    System.out.println(resultList.toString());
    return resultList;
}

I really appreciate your answers!

UPDATE

The content of the txt file looks like that:

complication, dilemma, lavender, issue, happy, weird

Line 32 ist that:

    String word = scan.next();

回答1:


Use :

while(scan.hasNext())

Instead of:

while(scan.hasNextLine())

hasNext is implemented to work with next() while hasNextLine is implemented to work with nextLine()



来源:https://stackoverflow.com/questions/27806974/java-util-nosuchelementexception-read-words-from-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!