Zähle Zeichen, Wörter und Zeilen in einer Datei

Dies sollte die Anzahl der Zeilen, Wörter und Zeichen in der Datei zählen.

Aber es geht nicht. Von der Ausgabe zeigt es nur0.

Code:

public static void main(String[] args) throws IOException {
    int ch;
    boolean prev = true;        
    //counters
    int charsCount = 0;
    int wordsCount = 0;
    int linesCount = 0;

    Scanner in = null;
    File selectedFile = null;
    JFileChooser chooser = new JFileChooser();
    // choose file 
    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        selectedFile = chooser.getSelectedFile();
        in = new Scanner(selectedFile);         
    }

    // count the characters of the file till the end
    while(in.hasNext()) {
        ch = in.next().charAt(0);
        if (ch != ' ') ++charsCount;
        if (!prev && ch == ' ') ++wordsCount;
        // don't count if previous char is space
        if (ch == ' ') 
            prev = true;
        else 
            prev = false;

        if (ch == '\n') ++linesCount;
    }

    //display the count of characters, words, and lines
    charsCount -= linesCount * 2;
    wordsCount += linesCount;
    System.out.println("# of chars: " + charsCount);
    System.out.println("# of words: " + wordsCount);
    System.out.println("# of lines: " + linesCount);

    in.close();
}

Ich kann nicht verstehen, was los ist. Irgendwelche Vorschläge?

Antworten auf die Frage(3)

Ihre Antwort auf die Frage