我制作了一个程序来计算数组中的元素。它可以工作,但是在我的程序中有一些错误。计算数组中的元素
我希望我的程序的输出是这样的:
1发生:2倍
2发生:1times
3发生:1times
6发生:1times
但我的程序给出了一个的这样的输出:
1发生:1times
1发生:2倍
2发生:1times
3发生:1times
6发生:1times
String[] values= {"1", "1", "3", "6", "2"};
int[] counts = new int[values.length];
Arrays.sort(values);
int temp = 0;
int c = 0;
for(int i = 0; i < values.length; i++){
counts[i] = Integer.parseInt(values[i]);
for(int j = 0;j < counts.length; j++) {
if(counts[i] == counts[j]) {
c++;
}
}
System.out.println(counts[i] + " occured: " + c +" times");
c = 0;
}
您可以使用hashmap来做到这一点。 – vikiiii
看看http://stackoverflow.com/questions/8098601/java-count-occurrence-of-each-item-in-an-array :) – sufinawaz
请避免没有大括号的statemts。 –