我有这个代码工作正常,但问题是结果显示如下。
public static int[] countlist (char[] list){
int [] counts = new int[list.length];
for (int k = 0; k < list.length; k++) {
for (int m = 0; m < list.length; m++) {
if (list[m] == list[k]){
counts[m]++;
}
}
System.out.println( "Letter " + list[k] + " = " + counts[k]);
}
}
输出:
Letter T = 1
Letter T = 2
Letter N = 1
Letter T = 3
Letter Z = 1
Letter N = 2
Letter H = 1
Letter H = 2
如何获取每个字母的输出一次? 非常感谢 例如,我希望输出如下所示
Letter T = 3
Letter N = 2
Letter Z = 1
Letter H = 2
答案 0 :(得分:3)
使用HashMap保存单个字符的计数/频率。
遍历您的列表并为每个元素执行:
最后,打印HashMap的键/值对将为您提供所需的输出。
答案 1 :(得分:0)
我不熟悉java但我现在可以快速输入代码,但基本上你可以创建一个数组,并且键是字母,值是字母值
在PHP中,这可以起到相似的作用:
$array = array();
$array['T'] = 1;
$array['T'] = 2;
$array['T'] = 3;
$array['N'] = 2;
$array['Z'] = 1;
$array['H'] = 2;
echo print_r($array); //Resulting in T=>3, N=>2, Z=>1, H=>2
如果你不想覆盖(例如)T的第一个值,你只需要实现一个IF语句,检查$ array ['T']是否已经存在。
编辑: 在您提供的代码中,您必须在我标记它的地方实现它:
public static int[] countlist (char[] list){
int [] counts = new int[list.length];
for (int k = 0; k < list.length; k++) {
for (int m = 0; m < list.length; m++) {
if (list[m] == list[k]){
counts[m]++;
}
}
//====Insert the code here====
System.out.println( "Letter " + list[k] + " = " + counts[k]);
}
}
答案 2 :(得分:0)
用于存储结果的原始数组是必需的?您可以使用Hashmap并将字母定义为键,将计数器定义为值。
Map<Character, Integer> charactersOccurrences = new HashMap<Character, Integer>();
for (int k = 0; k < list.length; k++) {
if (charactersOccurrences.containsKey(list[k])) {
charactersOccurrences.put(list[k], charactersOccurrences.get(k) + 1);
} else {
charactersOccurrences.put(list[k], 1);
}
}
然后打印:
for(char aLetter : charactersOccurrences.keySet()) {
System.out.println("Letter " + aLetter + " = " + charactersOccurrences.get(aLetter));
}
答案 3 :(得分:0)
public static void countlist (char[] list)
{
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int k = 0; k < list.length; k++)
{
if (map.containsKey(list[k]))
{
map.put(list[k], map.get(list[k]) + 1);
}
else
{
map.put(list[k], 1);
}
}
for (Map.Entry<Character, Integer> entry : map.entrySet())
{
System.out.println( "letter = " + entry.getKey() + ", count = " + entry.getValue() );
}
}