PDA

View Full Version : Sentence Input: String Manipulation


troublemaker
07-16-2008, 05:12 PM
hi,

i have a little problem. in this program i have a sentence which a user enters and then the the program displays the number of words and characters in the program. my first problem is that it should also display the average number of characters per WORD. what i have done i think it is even taking the spaces between words to mean characters. how do i just skip any white space and basically output the number of characters only including the letters in the word typed?

my other problem is that i also have to output the number of vowels and consonants in the entered sentence and am at a loss on how to start?

mport java.awt.*;
import hsa.Console;
import java.util.*;

public class SentenceInput
{
static Console c; // The output console

public static void main (String[] args)
{
c = new Console ();

String strSentence;
int sentenceLength, words;
double average;

do
{
c.println ("Enter a sentence or enter 0 to quit");
strSentence = c.readLine ();


if(strSentence.equals("0"))
{
break;
}

else if (strSentence.equals (""))
{
c.println ("Please enter a valid sentence");

}

StringTokenizer st = new StringTokenizer (strSentence);
words = st.countTokens ();
c.println (words);

sentenceLength = strSentence.length ();
c.println (sentenceLength);

average = sentenceLength / words;
c.println (average);
}

while (!strSentence.equals("0"));

}
}

shyam
07-16-2008, 08:13 PM
iterate through the tokens in the StringTokenizer and you will get the only the words, whose length you can add up to find the total characters in the words and since u already have the word count ;) you can calculate the average

troublemaker
07-16-2008, 10:04 PM
umm how do you "iterate"

jerry62704
07-18-2008, 06:27 PM
while (st.hasMoreTokens()) {
String x = st.nextToken();
System.out.println("x length:" + x.length());
for (int i = 0; i < x.length(); i++) {
// loop through word "x"
// test each character for vowel
// else it's a consonants
}
}

untested and you will have to figure out the character at to get each letter