0

Scanner returning NoSuch Element Exception error. Could you explain why is this happening.

The Scanner now passes and runs fine but it didn't take the nextLine input from the second Scanner call. This may be a little tweak but could someone point out what the mistake is.

public class JavaHW1_1 {

private static Scanner userInput = new Scanner(System.in);


public static void main(String[] args) throws IOException {

    String pattern ;
    String fileName = null;



    //      Method to manage user inputs 
    fileName = userInputFileName(userInput);
    pattern = userInputPattern(userInput);

    //      To find the pattern in the file
    //      findPattern();

}


private static String userInputPattern(Scanner userInput) {
    String pattern = "JollyGood";
    System.out.println(". Please enter a pattern to find in the file");

    while(userInput.hasNextLine()){
        pattern = userInput.nextLine();
        System.out.println("The pattern to be searched: "+ pattern);
    }
    userInput.close();

    return pattern;
}


private static String userInputFileName(Scanner userInput) throws IOException {
    String path = "./src";
    String files, fileName;
    File folder = new File(path);
    File[] listOfFiles = folder.listFiles();

    System.out.println("Please input the desired file name:\n");
    System.out.println("Some suggestions:\n");
     for (int i = 0; i < listOfFiles.length; i++) 
      {

       if (listOfFiles[i].isFile() && listOfFiles[i].getName().toLowerCase().endsWith(".txt")) 
       {

       files = listOfFiles[i].getName();
       System.out.println(files);
          }
      }

     int userAttempt = 0;

     do{
     fileName = userInput.nextLine();

     if(fileName.toLowerCase().endsWith(".txt")){
         System.out.println("The file name entered is in correct format");
         File file = new File("./src",fileName);

         try {
            file.createNewFile();
            System.out.println("File is created. Please enter text to be written in the file. End the content with \"eof\"");
            InputOutput(file.getName());
        } catch (IOException e) {
            e.printStackTrace();
        }

         userAttempt = 10;
     }
     else
         {System.out.println("Please enter correct format file with .txt extension");
         userAttempt++;}
     }while (userAttempt <10);

    return fileName;
}




private static void InputOutput(String fName) throws IOException {

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    BufferedWriter out = null;
    try {
        out = new BufferedWriter(new FileWriter("./src/" + fName));
        String inputLine = null;
        do {
            inputLine=in.readLine();
            out.write(inputLine);
            out.newLine();
        } while (!inputLine.equalsIgnoreCase("aaa"));
        System.out.print("Write Successful");
    } catch(IOException e1) {
        System.out.println("Error during reading/writing");
    } finally {
        out.close();
        in.close();
    }

}


private static void findPattern() {
    // TODO Auto-generated method stub

}


}
CtrlV
  • 115
  • 10
  • 2
    Please post the stacktrace. – Luiggi Mendoza Jun 11 '13 at 05:18
  • check this SO... http://stackoverflow.com/questions/15443383/scanner-nosuchelementexception are you opening the Scanner in another method? – fmodos Jun 11 '13 at 05:24
  • possible duplicate of http://stackoverflow.com/questions/7209110/java-util-nosuchelementexception-no-line-found – ajduke Jun 11 '13 at 05:29
  • ...I'm sorry, but I can't resist commenting. `SuccessfulException` is an oxymoron if I've ever read one. Please rename that class if you have control over it. – jpmc26 Jun 11 '13 at 05:33

2 Answers2

1

Based in this SO, you might be closing the Scanner and creating a new one to read from the System.in and it makes sense by looking at your code.

So my suggestion for you code is to receive the Scanner by parameter, something like this:

public static void main(String[] args){

    Scanner scan = new Scanner (System.in);
    String pattern = userInputPattern(scan);
    String test = readSomethingElse(scan);
}

private static String readSomethingElse(Scanner scan) {
   System.out.println(". Read something else");
    return scan.nextLine();
}

private static String userInputPattern(Scanner scan) {

    String pattern = "JollyGood";
    System.out.println(". Please enter a pattern to find in the file");
    pattern = scan.nextLine();
    System.out.println("The pattern to be searched: "+ pattern);
    return pattern;
}
Community
  • 1
  • 1
fmodos
  • 4,387
  • 1
  • 14
  • 17
  • 1
    Ah good one. I agree, maybe Scanner is backed by a buffer, if your try to scan using multiple Scanner, the input might already be 'eaten' by the preceding scanner's buffer – gerrytan Jun 11 '13 at 05:36
  • 1
    If the problem is open `Scanner`s, wouldn't it be better to do a `try { ... } finally { [close Scanner] }` or use Java 7's automatic resource management? – jpmc26 Jun 11 '13 at 05:37
  • @jpmc26 I haven't played with Java 7, so don't know how this would work... about the try/finally it is an interesting solution I will edit it and add to the answer as a second option. – fmodos Jun 11 '13 at 05:42
  • This helped so that I didn't get any error but it didn't ask for the input second time. My scan inputs are not simple to define in one method, there are multiple inputs in one method. – CtrlV Jun 11 '13 at 05:45
  • @jpmc26 about the try/finally solution, it doesnt work because the System.in is closed when the scanner is closed. – fmodos Jun 11 '13 at 05:48
  • @CtrlV maybe some logic in your code is broken, it should ask for the "second time" or many other times that the 'scan.nextLine' method is invoked... if you can post the full code or some more relevant code about it – fmodos Jun 11 '13 at 05:53
  • @CtrlV remove the line userInput.close(); this line close the System.in InputStream. – fmodos Jun 11 '13 at 06:00
  • Did removing that line worked for you? Actually it's not entering the while loop and if I remove the while condition it fails. – CtrlV Jun 11 '13 at 06:08
  • @CtrlV just found another issue on your code in the InputOutput method: `BufferedReader in = new BufferedReader(new InputStreamReader(System.in));` remove it and receive the Scanner by parameter – fmodos Jun 11 '13 at 06:18
  • @fmodos Can you point out how to use Scanner in place of BuueredReader? – CtrlV Jun 11 '13 at 21:23
  • @CtrlV `inputLine=in.readLine();` replace by `inputLine=scanner.nextLine()` – fmodos Jun 11 '13 at 21:25
  • @fmodos Do you mean to Vote Up for your answer. If yes I do not have permission right now but I will surely once I get qualifying reputation. – CtrlV Jun 11 '13 at 21:43
0

It could happen if you pass EOF straight into the standard input. For example (in windows):

java com.myprog.MainClass
^Z
Exception in thread "main" java.util.NoSuchElementException: No line found
  at java.util.Scanner.nextLine(Unknown Source)
  ....

The ^Z above represents a Ctrl-Z on windows command prompt which is an EOF signal

You need to consider your requirement and process / display error if user is provided a EOF without any prior data

gerrytan
  • 37,387
  • 8
  • 78
  • 91
  • It seems you may be correct but how should I correct it. Because if I end the content in previous scanner with any other string "eof" or ";" or "aaa" it still throws the same error. – CtrlV Jun 11 '13 at 05:33