-1

So i have the following code to open two files. filew2v contains words with newlines after each word. now I want to check if the words in filew2v exist in fileverb using the following code:

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");
            }
        }
    }
}
}

I call my method using:

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

I get the following error:

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

Could somebody point me to the right direction to look for my errors?

Soshiribo
  • 31
  • 5

2 Answers2

0

Looks like you have a blank line in the file, so hasNextLine() is returning true and next() method is not able to find any element and throwing the error.

Use hasNext() instead of hasNextLine().

Refer to scanner API here,

https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Santo
  • 362
  • 1
  • 4
  • 18
0

The logic is not correct . Your code checks the first word of file1 across entire file2 and if it doesnt find it ,it checks for second word but your file2 has already been scanned completely before so it wont find any element to check hence NoSuchElementException.

Store all content of second file in a string or in a collection and check against the file one.Hope this helps Similar example here

Community
  • 1
  • 1