简体   繁体   中英

Using scanner with a prompt and user input

I tried to do counting lines, words, character from user "inputted" file.
After this show counting and keep asking again.

If file doesn't exist print all data which have been counted during running.

Code:

public class KeepAskingApp {
    private static int lines;
    private static int words;
    private static int chars;

public static void main(String[] args) {
    boolean done = false;
    //counters
    int charsCount = 0, wordsCount = 0, linesCount = 0;
    Scanner in = null;  
    Scanner scanner = null;
    while (!done) {
        try {
            in = new Scanner(System.in);
            System.out.print("Enter a (next) file name: ");
            String input = in.nextLine();

            scanner = new Scanner(new File(input));     
            while(scanner.hasNextLine()) {
                lines += linesCount++;
                Scanner lineScanner = new Scanner(scanner.nextLine());
                lineScanner.useDelimiter(" ");
                while(lineScanner.hasNext()) {
                    words += wordsCount++;
                    chars += charsCount += lineScanner.next().length();
                }
                System.out.printf("# of chars: %d\n# of words: %d\n# of lines: ", 
                        charsCount, wordsCount, charsCount);

                lineScanner.close();
            }

            scanner.close();
            in.close();
        } catch (FileNotFoundException e) {
            System.out.printf("All lines: %d\nAll words: %d\nAll chars: %d\n", 
                    lines, words, chars);
            System.out.println("The end");
            done = true;
        } 
    }
}

}

But I can't understand why it always show output with no parameters:

All lines: 0
All words: 0
All chars: 0
The end

Why it omits all internal part.
It may be coz I'm using few scanners, but all look ok. Any suggestions?

UPDATE:

Thanks all who give some hint. I rethinking all constructed and rewrite code with newly info.
To awoid tricky scanner input line, I used JFileChooser :

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;

public class KeepAskingApp {
    private static int lines;
    private static int words;
    private static int chars;

    public static void main(String[] args) {
        boolean done = false;
        // counters
        int charsCount = 0, wordsCount = 0, linesCount = 0;
        Scanner in = null;
        Scanner lineScanner = null;
        File selectedFile = null;
        while (!done) {
            try {
                try {
                    JFileChooser chooser = new JFileChooser();

                    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                        selectedFile = chooser.getSelectedFile();
                        in = new Scanner(selectedFile);
                    }
                    while (in.hasNextLine()) {
                        linesCount++;
                        lineScanner = new Scanner(in.nextLine());
                        lineScanner.useDelimiter(" ");
                        while (lineScanner.hasNext()) {
                            wordsCount++;
                            charsCount += lineScanner.next().length();
                        }

                    }
                    System.out.printf(
                            "# of chars: %d\n# of words: %d\n# of lines: %d\n",
                            charsCount, wordsCount, linesCount);

                    lineScanner.close();
                    lines += linesCount;
                    words += wordsCount;
                    chars += charsCount;

                    in.close();
                } finally {
                    System.out.printf(
                            "\nAll lines: %d\nAll words: %d\nAll chars: %d\n",
                            lines, words, chars);
                    System.out.println("The end");
                    done = true;
                }
            } catch (FileNotFoundException e) {
                System.out.println("Error! File not found.");
            }
        }
    }
}

Couple of issues (actually there are many issues with your code, but I will address the ones directly related to the output you have posted):

First of all, the stuff in the catch block only happens if you get a FileNotFoundException ; that's there to handle and recover from errors. I suspect you meant to put a finally block there, or you meant to do that after the catch . I suggest reading this tutorial on catching and handling exceptions , which straightforwardly describes try , catch , and finally .

Once you read that tutorial, come back to your code; you may find that you have a little bit of reorganizing to do.

Second, with the above in mind, it's obvious by the output you are seeing that you are executing the code in that catch block, which means you are getting a FileNotFoundException . This would be caused by one of two (possibly obvious) things:

  1. The file you entered, well, wasn't found. It may not exist or it may not be where you expect. Check to make sure you are entering the correct filename and that the file actually exists.

  2. The input string is not what you expect. Perhaps you read a blank line from previous input, etc.

Addressing reason 2: If there is already a newline on the input buffer for whatever reason, you will read a blank line with Scanner . You might want to print the value of input just before opening the file to make sure it's what you expect.

If you're seeing blank lines, just skip them. So, instead of this:

String input = in.nextLine();
scanner = new Scanner(new File(input));     

Something like this instead would be immune to blank lines:

String input;
do {
    input = in.nextLine().trim(); // remove stray leading/trailing whitespace
} while (input.isEmpty()); // keep asking for input if a blank line is read
scanner = new Scanner(new File(input));

And, finally, I think you can work out the reason that you're seeing 0's in your output. When you attempt to open the file with new Scanner(new File(input)); and it fails because it can't find the file, it throws an exception and the program immediately jumps to the code in your catch block. That means lines , words , and chars still have their initial value of zero (all code that modifies them was skipped).

Hope that helps.

Your println() s are in a catch block

    } catch (FileNotFoundException e) {
        System.out.printf("All lines: %d\nAll words: %d\nAll chars: %d\n", 
                lines, words, chars);
        System.out.println("The end");
        done = true;
    }

That means you caught a FileNotFoundException . I think you can figure out from here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM