Cus*_*ase 4 java arrays sorting string
这应该很简单(我认为),但我无法做到正确......:|
任务如下:
询问用户一些输入.必须将输入拆分为单个单词并放入数组中.应该计算所有单词.如果存在相等的单词,则它们在输出上得到"+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[?] );
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Hashmap来执行此操作.Hashmap存储键值对,每个键必须是唯一的.
所以在你的情况下,一个键将是你已经拆分的字符串的一个单词,值将是它的计数.
将输入拆分为单词并将其放入字符串数组后,将第一个单词(作为键)放入Hashmap中,将1作为值.对于每个后续单词,您可以使用函数containsKey()将该单词与Hashmap中的任何现有键进行匹配.如果它返回true,则将该键的值(count)递增1,否则将word和1作为新的键值对放入Hashmap中.
| 归档时间: |
|
| 查看次数: |
7814 次 |
| 最近记录: |