Skip to content
Advertisement

Count words, java

I want to count words. I use the methods hasNextChar and getChar. The sentence may contain all kind of chars. Here’s my code:

        boolean isWord = false;

        while(hasNextChar()){
            char current = getChar();   
            switch(current){
                case ' ' : case '.' : case ',' : case '-' :
                    isWord = false;
                default:
                    if(!isWord) wordCount++;
                    isWord = true;
            }
        }

It works so far but e.g. when I have a ” . ” at the end it gives me 8 instead of 7 words. Here are some examples of sentences:

*„Schreiben Sie ein Praktikanten-Vermittlungs-Programm“ – words: 6

„Du magst ja recht haben – aber ich sehe das ganz anders.“ – words: 11

„Hallo Welt !!!!“ – words: 2

„Zwei Wörter !!!!“ – words: 2

„Eins,Zwei oder Drei“ – words: 4*

A sentence does not have to end with a ” . “.

Any ideas how to solve that?

Advertisement

Answer

You forgot the break statement in the first case (after isWord = false).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement