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.");
}
}
You need to read entire line. Instead of in.next();
use in.nextLine()
.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With