0

I am a beginner with java and programmin over all, So this the full code for a file reader program that counts words or displays text file content, I wanted to take user inputs for commands that I indicated using an if statement, but String printFileCommand = scan.nextLine(); is not working due to the error addressed below:


    package com;
    
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    
    public class FileReader {
      public static void main(String[] args) throws FileNotFoundException {
        Scanner scanTwo = new Scanner(System.in);
        System.out.println("Please Enter Your File Path");
        String filePath = scanTwo.nextLine(); 
        scanTwo.close(); 
        File fileInput = new File(filePath);
        Scanner fileScanner = new Scanner(fileInput);
        System.out.println(fileScanner.nextLine());
        fileScanner.close();
        System.out.println("Commands: PRINT.FILE --> Prints all file    COUNT.WORDS --> Counts all words");
        System.out.println("Type Command:");
        
        Scanner scan = new Scanner(System.in);
        String printFileCommand = scan.nextLine();   <----ERROR HERE
        scan.close();
         
         
         if (printFileCommand.contains("PRINT.FILE")) {
           while (fileScanner.hasNextLine()) {
             System.out.println(fileScanner.nextLine());
            }
          } else if (printFileCommand.contains("COUNT.WORDS")) {
            int wordCount = 0;
            while (fileScanner.hasNext()) {
              String fileWords = fileScanner.next();
              wordCount++;
              // System.out.println(wordCount); 
            }
            System.out.println(wordCount);
          } 
          else {
            System.out.println("COMMAND INVALID!");
          }
        } 
      }
    ```

**Terminal Output:**

PS C:\Users\DR\Desktop\FIRST REAL PROGRAMMING>  c:; cd 'c:\Users\DR\Desktop\FIRST REAL PROGRAMMING'; & 'c:\Users\DR\.vscode\extensions\vscjava.vscode-java-debug-0.30.0\scripts\launcher.bat' 'C:\Program Files\AdoptOpenJDK\jdk-15.0.1.9-hotspot\bin\java.exe' '--enable-preview' '-XX:+ShowCodeDetailsInExceptionMessages' '-Dfile.encoding=UTF-8' '-cp' 'C:\Users\DR\AppData\Roaming\Code\User\workspaceStorage\458dc35931a3067a355426e5ceeeee32\redhat.java\jdt_ws\FIRST REAL PROGRAMMING_e263b9bc\bin' 'com.FileReader'
Please Enter Your File Path
E://texttwo.txt
This is my text file.
Commands: PRINT.FILE --> Prints all file    COUNT.WORDS --> Counts all words
Type Command:
Exception in thread "main" java.util.NoSuchElementException: No line found
        at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
        at com.FileReader.main(FileReader.java:21)
PS C:\Users\DR\Desktop\FIRST REAL PROGRAMMING>

So why is `String printFileCommand = scan.nextLine();` not working? I tried alot, but its not working...
Omar Faris
  • 11
  • 2
  • Does this answer your question? [java.util.NoSuchElementException - Scanner reading user input](https://stackoverflow.com/questions/13042008/java-util-nosuchelementexception-scanner-reading-user-input) – Tom Feb 02 '21 at 02:04

3 Answers3

0

It doesn't work because your stream for System.in is closed. You can check it for example System.out.println(System.in.available()); and you will see:

Exception in thread "main" java.io.IOException: Stream closed
at java.io.BufferedInputStream.getInIfOpen(BufferedInputStream.java:159)
at java.io.BufferedInputStream.available(BufferedInputStream.java:410)

you closed it in line: scanTwo.close();

arch2be
  • 306
  • 2
  • 8
0

I'm still trying to understand Java myself, but I think you don't exactly need to create and use multiple Scanners to collect data. Since you are searching for strings for the file creations, you could technically do something like:

Scanner scanner = new Scanner(System.in);

String filePath = scanner.nextLine();

With some of the other scanners you can keep since you're specifically calling the fileInputs within the Scanner, but when asking the user for data, I suggest using only one scanner source, but having something like the last line of code I shared as a template for updating your code! If I misunderstood something you're more than welcome to let me know. Thanks!

-1

Please check this question: NoSuchElementException - class Scanner

Your code will work if you remove the code:

  scanTwo.close();

Or removing better:

  Scanner scan = new Scanner(System.in);

And use scanTwo for reading (but you don't have to close the scanner with scanTwo.close()).

But I recommend you to read those answers to understand how it works.

Edgar Magallon
  • 556
  • 2
  • 7
  • 15