java.util.NoSuchElementException:从文件中读取单词
java.util.NoSuchElementException: Read words from a file
这个简单的 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)
正如你所看到的,我得到了这些词,但是我也得到了一个例外。我正在使用以下代码:
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 程序有什么问题?
我正在尝试从文件中读取单词并出现以下异常:
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)
正如你所看到的,我得到了这些词,但是我也得到了一个例外。我正在使用以下代码:
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()