Question

The objective is to get a sentence input from the user, tokenize it, and then give information about the first three words only (word itself, length, and then average the first 3 word lengths). I'm not sure how to turn the tokens into strings. I just need some guidance - not sure how to proceed. I've got this so far:

public static void main(String[] args) {

    String delim = " ";

    String inSentence = JOptionPane.showInputDialog("Please enter a sentence of three or more words: ");

    StringTokenizer tk = new StringTokenizer(inSentence, delim);

    int sentenceCount = tk.countTokens();


    // Output
    String out = "";
    out = out + "Total number of words in the sentence: " +sentenceCount +"\n";

    JOptionPane.showMessageDialog(null, out);


}

I'd really appreciate any guidance!

Was it helpful?

Solution

If you just wanted to get the first 3 tokens, then you could do something like this:

String first = tk.nextToken();
String second = tk.hasMoreTokens() ? tk.nextToken() : "";
String third = tk.hasMoreTokens() ? tk.nextToken() : "";

From there should be pretty easy to calculate the other requirements

OTHER TIPS

public static void main(String[] args) {

    String delim = " ";

    String inSentence = JOptionPane.showInputDialog("Please enter a sentence of three or more words: ");

    StringTokenizer tk = new StringTokenizer(inSentence, delim);

    int sentenceCount = tk.countTokens();

    // Output
    String out = "";
    out = out + "Total number of words in the sentence: " +sentenceCount +"\n";

    JOptionPane.showMessageDialog(null, out);

    int totalLength = 0;
    while(tk.hasMoreTokens()){
        String token = tk.nextToken();
        totalLength+= token.length();
        out = "Word: " + token + " Length:" + token.length();
        JOptionPane.showMessageDialog(null, out);
    }

    out = "Average word Length = " + (totalLength/3);
    JOptionPane.showMessageDialog(null, out);
}

The way to get the individual strings by using nextToken().

while (tk.hasMoreTokens()) {
  System.out.println(st.nextToken());
}

You're free to do anything else than printing them, of course. If you only want the three first tokens, you might not want to use a while loop but a couple of simple if statements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top