目标是从用户那里获得一个句子输入,对其进行标记,然后只给出关于前三个单词的信息(单词本身、长度,然后计算前三个单词长度的平均值)。我不确定如何将令牌转换为字符串。我只是需要一些指导-不知道如何进行。到目前为止我已经明白了:
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);
}
我真的很感激任何指导!
如果您只想获得前3个标记,那么您可以这样做:
String first = tk.nextToken();
String second = tk.hasMoreTokens() ? tk.nextToken() : "";
String third = tk.hasMoreTokens() ? tk.nextToken() : "";
从那里应该很容易计算其他需求
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);
}
使用nextToken()
获取单个字符串的方法。
while (tk.hasMoreTokens()) {
System.out.println(st.nextToken());
}
当然,除了打印它们之外,您可以自由地做任何其他事情。如果您只想要前三个令牌,则可能不希望使用while
循环,而是使用几个简单的if
语句。