Search code examples
javastringword-count

Letter count in sentence not counting last word


I am new to java programming. This snippet calculates no of letters in each word and stores it as a string(excluding the spaces) but it is only calculating till "large" and not counting no of letters in "container".

class piSong
{
    String pi = "31415926535897932384626433833";
    public void isPiSong(String exp)
    {
        int i,count=0;
        String counter = "";
        String str;
        System.out.println(exp.charAt(25));
        for(i=0;i<exp.length()-1;i++)
        {
            if(Character.isWhitespace(exp.charAt(i)))
            {   str = Integer.toString(count);
                counter += str;
                count = 0;
                continue;
            }
            count++;

        }
        System.out.println(counter);
    }
}
public class isPiSong{
    public static void main(String[] args)
    {
        piSong p = new piSong();
        String exp = "can i have a large container";
        p.isPiSong(exp);
    }
} 

expected output:314157

current output: 31415


Solution

  • There are 2 things you should fix.

    1. In your for loop, your condition is i<exp.length()-1. Why? You obviously want to include the last character also (which is charAt(exp.length() -1)), so you condition should either be i <= exp.length() -1 or i < exp.length().

    2. You logic is to count the letters whenever you encounter a whitespace. But after counting the last word, you dont have a whitespace. That's why it's not counting the last word.

    To Fix, append count to counter after the loop.

    // Loop ends here
    counter += count;
    System.out.println(counter);