Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Beginner - Counting number of words in sentence

Tags:

java

methods

I am suppose to use methods in order to count number of words in the a sentence. I wrote this code and I am not quite sure why it doesn't work. No matter what I write, I only receive a count of 1 word. If you could tell me how to fix what I wrote rather than give me a completely different idea that would be great:

import java.util.Scanner;

public class P5_7 
{
    public static int countWords(String str)
    {
        int count = 1;
        for (int i=0;i<=str.length()-1;i++)
        {
            if (str.charAt(i) == ' ' && str.charAt(i+1)!=' ')
            {
                count++;
            }
        }
        return count;
    }
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String sentence = in.next();
        System.out.print("Your sentence has " + countWords(sentence) + " words.");
    }
}
like image 543
ohoh7171 Avatar asked Dec 20 '22 07:12

ohoh7171


2 Answers

You need to read entire line. Instead of in.next(); use in.nextLine().

like image 142
Pshemo Avatar answered Jan 05 '23 16:01

Pshemo


An easy way to solve this problem:

return str.split(" ").length;

Or to be more careful, this is how you'd take into account more than one whitespace:

return str.split("\\s+").length;
like image 26
Óscar López Avatar answered Jan 05 '23 14:01

Óscar López