java.util.NoSuchElementException:从文件中读取单词 [英] java.util.NoSuchElementException: Read words from a file

查看:41
本文介绍了java.util.NoSuchElementException:从文件中读取单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个简单的Java程序怎么了?

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;
}

非常感谢您的回答!

更新

txt文件的内容如下:

The content of the txt file looks like that:

complication, dilemma, lavender, issue, happy, weird

第32行提示:

    String word = scan.next();

推荐答案

使用:

while(scan.hasNext())

代替:

while(scan.hasNextLine())

hasNext 实现为与 next()一起使用,而 hasNextLine 实现为与 nextLine()一起使用

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

这篇关于java.util.NoSuchElementException:从文件中读取单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆