import java.util.Scanner; public class WordCount { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter your string:"); String str = in.next(); countWords(str); System.out.print(countWords(str)); } public static int countWords(String str) { int count = 0; for (int i = 0; i < str.length()-1; i++) { if ((str.charAt(i)==' ')&&(!(str.charAt(i+1)==' '))) { count++; } } return count; } } This is my code for counting the number of words in a string. This program compiles, but the answer is always 0. I don't know why the program is not considering the increment of count. I would appreciate help in this. Thanks!
import java.util.Scanner; public class WordCount { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter your string:"); String str = in.next(); countWords(str); System.out.print(countWords(str)); } public static int countWords(String str) { int count = 0; for (int i = 0; i < str.length()-1; i++) { if ((str.charAt(i)==' ')&&(!(str.charAt(i+1)==' '))) { count++; } } return count; } } This is my code for counting the number of words in a string. This program compiles, but the answer is always 0. I don't know why the program is not considering the increment of count. I would appreciate help in this. Thanks!
Related questions
Question
100%
import java.util.Scanner;
public class WordCount
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter your string:");
String str = in.next();
countWords(str);
System.out.print(countWords(str));
}
public static int countWords(String str)
{
int count = 0;
for (int i = 0; i < str.length()-1; i++)
{
if ((str.charAt(i)==' ')&&(!(str.charAt(i+1)==' ')))
{
count++;
}
}
return count;
}
}
This is my code for counting the number of words in a string. This
Expert Solution

This question has been solved!
Explore an expertly crafted, step-by-step solution for a thorough understanding of key concepts.
This is a popular solution!
Trending now
This is a popular solution!
Step by step
Solved in 2 steps with 1 images

Knowledge Booster
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.