我的代码有问题。有3个类和文本文件:Main
,Listener
,Unduplicator
和Dictionary.txt
。如果我输入单词,程序必须检查Dictionary.txt
中是否存在该单词。如果没有,则必须在Dictionary.txt
中保存该单词。我做错了,在我写下文字后崩溃并显示信息
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at FIMP.Listener.TextFrom(Listener.java:8)
at FIMP.Unduplicator.<init>(Unduplicator.java:13)
at FIMP.Main.main(Main.java:11
我不知道如何解决它。
Class Main
package FIMP;
import java.io.IOException;
public class Main {
public static void main (String args[]) throws IOException{
Listener listener = new Listener();
listener.TextFrom();
Unduplicator unduplicator = new Unduplicator();
}
}
Class Listener
package FIMP;
import java.util.*;
public class Listener{
public String TextFrom(){
Scanner TextScan = new Scanner(System.in);
String ST = TextScan.next();
TextScan.close();
return ST;
}
}
Class Unduplicator
package FIMP;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Unduplicator {
public Unduplicator() throws IOException{
Listener listener = new Listener();
String word = listener.TextFrom();
Scanner scanner = new Scanner("Dictionary.txt");
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(word)){
System.out.println("Word EXIST");
}
else{
FileWriter TextStream = new FileWriter("Dictionary.txt", true);
TextStream.write(listener.TextFrom() + "\n");
TextStream.close();
}
scanner.close();
}
}
}
答案 0 :(得分:0)
问题在于您执行以下操作:
Scanner TextScan = new Scanner(System.in);
...
TextScan.close();
调用close()时,也会关闭基础流。在这种情况下:System.in。通常不建议这样做。请仅使用单个扫描仪实例,而不要关闭它。
答案 1 :(得分:0)
在你的主要方法中,你正在调用
Listener listener = new Listener();
listener.TextFrom();
关闭System.in
然后在Unduplicator
试图致电
Listener listener = new Listener();
String word = listener.TextFrom(); // but System.in is closed