gpt4 book ai didi

java.util.NoSuchElementException : Read words from a file

转载 作者:行者123 更新时间:2023-12-02 05:05:50 25 4
gpt4 key购买 nike

这个简单的 java 程序有什么问题?

我试图从文件中读取单词并得到以下异常:

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)

正如你所看到的,我得到了这些话,但是,我也得到了一个异常(exception)。我正在使用以下代码:

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 文件的内容如下所示:

complication, dilemma, lavender, issue, happy, weird

第 32 行是:

    String word = scan.next();

最佳答案

用途:

while(scan.hasNext())

而不是:

while(scan.hasNextLine())

hasNext 实现为与 next() 配合使用,而 hasNextLine 实现为与 nextLine() 配合使用

关于java.util.NoSuchElementException : Read words from a file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27806974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com