Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

hi guys, i\'m having a bit of trouble. Can you guys help? A gentleman on cramste

ID: 3631928 • Letter: H

Question

hi guys, i'm having a bit of trouble. Can you guys help? A gentleman on cramster helped me earlier to write a code that takes user input and then counts the number of words the user input. in order to help me understand the algorithm i revised it. However, it doesnt work. How can i fix it? this is my code:

import java.util.*;
import java.io.*;
public class Wordcount
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int repeat=0;
int num=0;
int length;
int count;
String phrase;
char ch;
System.out.print("Enter a phrase please.");
phrase = in.nextLine();
length=phrase.length();
for (count=1;count<length;count++)
{
ch=phrase.charAt(count);
if (ch == " ")
repeat = 0;
else if (ch != " " && repeat =0)
repeat = 2;
num= num+1;
}
System.out.println("total number of words: "+num);
}
}


basically it is saying that i cant use ch== " " as well as ch!= " "
there might be other things wrong with it, but so far the compiler on jGrasp said those were the only two errors it found. What is wrong with this? How can i revise it so that it can take user input and then output the number of words the user input

for example the user input might be:
Hey guys I'm trying to write a program
the output should be
the total number of words is 8

But as of right now I cannot even compile it. Help please! thanks!

Explanation / Answer

Hi, I have make some amendments. Basically, the algorithm is like this. The (number of words in the sentence) is actually the (number of spaces in the sentence +1). Therefore, we have to count the number of spaces in the sentence. In the for loop for the if statement, we can use character to compare with string. Therefore, we have to create a character of a spacing, below is how i did it. String spacing = " "; char space = spacing.charAt(0); ------------------------------------------------------------------------------------------------ import java.util.*; import java.io.*; public class Wordcount { public static void main(String[] args) { Scanner in=new Scanner(System.in); int repeat=0; int num=0; int length; int count; String phrase; char ch; String spacing = " "; char space = spacing.charAt(0); System.out.print("Enter a phrase please."); phrase = in.nextLine(); length=phrase.length(); for (count=0;count