我正在尝试编写一个 java 程序,该程序将计算声明的句子中的单词数,然后将句子分解为单词,以便列出具有数值的单词并显示单词。我已经解决了总数,但我似乎无法分解句子中的单词然后按时间顺序列出它们。我可以用字符做到这一点,但不能用文字。
我已经探索了 Java Cookbook 和其他地方以找到解决方案,但我只是不太了解它。正如我所说,我可以让字符计数,我可以计算单词,但我不能让单个单词在单独的行上打印,并在字符串中使用数值来表示它们的计数。
public class MySentenceCounter {
public static void main(String[] args) {
String sentence = "This is my sentence and it is not great";
String[] wordArray = sentence.trim().split("\\s+");
int wordCount = wordArray.length;
for (int i=0; i < sentence.length( ); i++)
System.out.println("Char " + i + " is " + sentence.charAt(i));
//this produces the character count but I need it to form words, not individual characters.
System.out.println("Total is " + wordCount + " words.");
}
}
预期结果应如下所示:
1 This
2 is
3 my
4 sentence
5 and
6 it
7 is
8 not
9 great
Total is 9 words.
繁星点点滴滴
饮歌长啸
qq_花开花谢_0
相关分类