0

I am trying to make a program that imports a text file and analyzes it to tell me if another text file has possible match up sentences. I keep running into this error when I import my file and attempt to analyze it. I am assuming that I am missing something in my code.

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)

Heres my code too:

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

The second scanner I havent completed yet either. Any suggestions?

4

2 回答 2

2

We need more info to conclusively answer, but check out the documentation for next(). It throws this exception when there's no next element. My guess is it's because of this part:

String fileName = testScan.nextLine();

You're not checking if hasNextLine first.

于 2013-10-30T18:31:03.093 回答
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 */
    }
}
于 2013-10-30T18:28:44.360 回答