{Java} Counting how many words are in a sentence?
Go to solution
Solved by Mefoga,
public class sentence{
public static void main(String args[]){
System.out.print("input a sentence: ");
String line;
EasyReader input = new EasyReader():
line = input.readLine():
int count = 1;
for(int i = 0;i < line.length();i++)
{
if(line.charAt(i) == ' ')
count++;
}
if(count > 2)
System.out.println("There are more than 2 words.");
else
System.out.println("There are 2 or fewer words.");
}
}
Of course this isn't safe to all stupid end users, with cases that won't work being where the string is just a space, the string is just a word with a space before and/or after the actual word, or multiple spaces. I was just assuming correct grammar with mine, making it very simple.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now