2

目标是从用户那里得到一个句子输入,对其进行标记,然后只给出关于前三个单词的信息(单词本身、长度,然后平均前 3 个单词的长度)。我不确定如何将标记转换为字符串。我只需要一些指导 - 不知道如何进行。到目前为止我有这个:

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);


}

我真的很感激任何指导!

4

3 回答 3

1

如果您只想获得前 3 个令牌,那么您可以执行以下操作:

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

从那里应该很容易计算其他要求

于 2013-05-24T00:42:32.923 回答
1
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);
}
于 2013-05-24T00:46:19.337 回答
0

使用nextToken().

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

当然,除了打印它们之外,您可以自由地做任何事情。如果您只想要前三个标记,您可能不想使用while循环,而是使用几个简单的if语句。

于 2013-05-24T00:42:38.493 回答