我正在尝试创建一个导入文本文件的程序并对其进行分析,以告诉我其他文本文件是否有匹配的句子。导入文件并尝试分析时,我一直遇到此错误。我假设我在代码中遗漏了一些内容。
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at PossibleSentence.main(PossibleSentence.java:30)
也是我的代码:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class PossibleSentence {
public static void main(String[] args) throws FileNotFoundException{
Scanner testScan = new Scanner(System.in);
System.out.print("Please enter the log file to analyze: ");
String fileName = testScan.nextLine();
File f = new File(fileName);
Scanner scan = new Scanner(f);
String line = null;
int i = 0;
while (scan.hasNextLine()) {
String word = scan.next();
i++;
}
scan.close();
File comparative = new File("IdentifyWords.java");
Scanner compare = new Scanner(comparative);
String line2 = null;
}
}
我还没完成第二台扫描仪。有什么建议吗?
答案 0 :(得分:2)
我们需要更多信息才能最终回答,但请查看the documentation for next()。当没有下一个元素时,它会抛出此异常。我的猜测是因为这部分:
String fileName = testScan.nextLine();
您不是先检查是否hasNextLine
。
答案 1 :(得分:0)
您正在将文件参数传递给Scanner
对象,请尝试使用InputStream
File input = new File(/* file argument*/);
BufferedReader br = null;
FileReader fr= null;
Scanner scan = null;
try {
fr = new FileReader(input);
br = new BufferedReader(fr);
scan = new Scanner(br);
/* Do logic with scanner */
} catch (IOException e) {
/* handling for errors*/
} finally {
try {
if (br != null) {
br.close();
}
if (fr != null) {
fr.close();
}
if (scan != null) {
scan.close();
}
} catch (IOException e) {
/* handle closing error */
}
}