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 on
The simple logic is count the spaces only if there aren't any white spaces before. Try this:
public class WordCount
{
public static void main(String[] args)
{
int word=1;
Scanner s = new Scanner(System.in);
System.out.println("Enter a string: ");
String str=s.nextLine();
for(int i=1;i<str.length();i++)
{
if(str.charAt(i)==' ' && str.charAt(i-1)!=' ')
word++;
}
System.out.println("Total Number of words= "+word);
}
}
Try This Simple Code with split() and argument as spaces
int length=str.split(" ").length;
It will return number of words in your sentence.
package test;
public class CommonWords {
public static void main(String[] args) {
String words = "1 2 3 44 55 966 5 88 ";
int count = 0;
String[] data = words.split(" ");
for (String string : data) {
if (!string.equals("")) {
count++;
}
}
System.out.println(count);
}
}
You need to read entire line. Instead of in.next();
use in.nextLine()
.
This program works fine,
step1:input the string
step2:split the string into single word store in a arrays
step3 :return the length of the arrays
public class P5_7
{
public static int countWords(String str)
{
String words[]=str.split(" ");
int count=words.length;
return count;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence =in.nextLine();
System.out.print("Your sentence has " + countWords(sentence) + " words.");
}
}