2016-09-14 32 views
-1

因此,我有以下代码来打开两个文件。 filew2v包含每个单词后面带有换行符的单词。现在我要检查,如果使用下面的代码在fileverb存在filew2v的话:使用扫描器检查file1中是否存在file1中的字NoSuchElementException

public class CompareWords { 
public void CompareWordsOK(File fileverb, File filew2v) throws IOException { 
    Scanner scannerw2v = new Scanner(filew2v); 
    Scanner scannerverb = new Scanner(fileverb); 
    while (scannerw2v.hasNextLine()) { 
     String nextToken1 = scannerw2v.next(); 
     while (scannerverb.hasNextLine()) { 
      String nextToken = scannerverb.next(); 
      if (nextToken.equalsIgnoreCase(nextToken1)) { 
       System.out.print("EXIST"); 
      } 
     } 
    } 
} 
} 

我打电话给我的方法使用:

compverb.CompareVerbOK(new File("/home/user/Desktop/listOfwords.txt"), new File("/home/user/Desktop/listofwordsforchecking.txt")); 

我收到以下错误:

Exception in thread "main" java.util.NoSuchElementException 
at java.util.Scanner.throwFor(Scanner.java:862) 
at java.util.Scanner.next(Scanner.java:1371) 
at CompareVerb.CompareVerbOK(CompareVerb.java:13) 
at Main.main(Main.java:11) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
at java.lang.reflect.Method.invoke(Method.java:498) 
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147 

有人可以指点我正确的方向来寻找我的错误吗?

回答

0

的逻辑是不正确的。你的代码在整个文件2中检查file1的第一个单词,如果它没有找到它,它检查第二个单词,但是你的file2已经完全扫描了,所以它不会找到任何元素来检查NoSuchElementException。

存储在一个字符串或在收集和核对文件第二个文件中的所有内容one.Hope这有助于 类似的例子here

相关问题