【发布时间】:2012-09-11 20:56:42
【问题描述】:
这应该很简单(我认为),但我就是无法正确...:|
任务如下:
询问用户一些输入。输入必须拆分为单个单词并放入数组中。所有单词都应该被计算在内。如果存在相同的单词,它们会在输出中得到“+1”。 最后,我想打印出列表中正确数量的计数单词。我的前两列是正确的,但是相同单词的单词计数器让我很头疼。如果一个词被发现是相等的,它就不能在生成的列表中出现两次! :!
我是一个完整的 JAVA 新手,所以请善待代码判断。 ;)
到目前为止,这是我的代码:
package MyProjects;
import javax.swing.JOptionPane;
public class MyWordCount {
public static void main(String[] args) {
//User input dialog
String inPut = JOptionPane.showInputDialog("Write som text here");
//Puts it into an array, and split it with " ".
String[] wordList = inPut.split(" ");
//Print to screen
System.out.println("Place:\tWord:\tCount: ");
//Check & init wordCount
int wordCount = 0;
for (int i = 0; i < wordList.length; i++) {
for (int j = 0; j < wordList.length; j++){
//some code here to compare
//something.compareTo(wordList) ?
}
System.out.println(i + "\t" + wordList[i]+ "\t" + wordCount[?] );
}
}
}
【问题讨论】:
-
也许我应该用一个 for-each 循环来改变两个 for-loop?
-
使用
List<String> words = Arrays.asList(inPut.split(" "));,然后使用Collections.frequency(words, word)确定单词的实例数。 -
这个问题的回答还没有让您满意吗?您需要更多信息吗?
-
一切都好! :) 感谢所有提示!
-
@Mechanicalsnail 感谢您的提醒。虽然我认为我的评论是在此更改之前发表的,但很高兴知道未来。
标签: java arrays string sorting