I need to know what I'm doing wrong here..
Here is my objective:
Write a program to read a sentence (a String) entered by the user and display the following statistics:
1. the number of words in the sentence;
2. the length of each word (the number of characters);
3. the length of the longest word; and
4. the length of the shortest word
5. assume that the phrase will always end with punctuation and the punctuation will not be counted as a character in the computation of the length.
example:
Please enter the sentence to analyse:
Assignment2 may require a loop!
Here are some statistics on your sentence:
Word 1 has 11 characters.
Word 2 has 3 characters.
Word 3 has 7 characters.
Word 4 has 1 character.
Word 5 has 4 characters.
There are 5 words.
The longest word has 11 characters.
The shortest word has 1 character.
Press any key to continue...
Now I was able to code enough to find the amount of words in a string, but I'm stuck when I try to compute the length of each word :(
If anybody can help, it would be greatly appreciated
Oh and I CANNOT use StringTokenizer :(
My code:
import java.util.Scanner;
public class Assignment_2
{
public static void main (String args[])
{
Scanner userInput = new Scanner(System.in);
String a = "";
a = userInput.nextLine();
int textLength = a.length();
int numberOfWords = 0;
int countChar = 0;
boolean isWord = false;
for (int i=0;i<textLength;i++)
{
if (a.charAt(i) == ' ' || a.charAt(i) == '.'|| a.charAt(i) == '?' || a.charAt(i) == '!')
{
numberOfWords++; \\when a space or a punctuation is found, increment number of words by one
isWord = true; \\ flag isWord as true when ending of a word is found
}
else
{
countChar++; \\ otherwise we are inside a word and we need to increment the character count
}
\\ I tried to put a while (isTrue) statement here, but it just loops on forever.
}
System.out.println("Word " + numberOfWords);
}
}