[英]sorting an array and counting its elements
I tried to sort an array accending and count the array elements please help me find whats missing, have debugged many times. 我试图对数组进行排序并计算数组元素,请帮助我查找缺少的内容,已调试了很多次。 here is my code and the output i got. 这是我的代码和我得到的输出。 Thanks 谢谢
package habeeb;
import java.util.*;
public class Habeeb {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = new int[30];
int i, count=0;
System.out.println("Enter the integers between 1 and 100" );
for( i=0; i<num.length; i++){
num[i]= input.nextInt();
if(num[i]==0)
break;
count++;
}
calling the function here 在这里调用函数
Sorting(num, i, count);
}
public static void Sorting(int[] sort, int a, int con){
if (a<0) return;
/*am sorting the array here*/
Arrays.sort(sort);
int j, count=0;
for(j=0; j<con; j++){
if(sort[a]==sort[j])
count++;
}
System.out.println(sort[a]+" occurs "+count+" times");
Sorting(sort, a-1, con);
}
}
Here is the output: 这是输出:
run:
Enter the integers between 1 and 100
2
5
4
8
1
6
0
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
Your problem is that the array is of size 30 and when you sort it you have all the values you did not assign to equal to 0 and thus they go in the front of the sorted array. 您的问题是该数组的大小为30,并且在对它进行排序时,您没有分配的所有值都等于0,因此它们位于已排序数组的前面。 Later on out of the first 6 numbers all are 0 so the output you have is correct. 之后的前6个数字全为0,因此输出正确。
To aviod the problem you face I suggest you use ArrayList
instead of simple array so that you can add elements dynamically to it. 为了避免您遇到的问题,我建议您使用ArrayList
而不是简单数组,以便可以向其中动态添加元素。
You are doing a bit more work than is necessary. 您所做的工作比必要的多。 I would solve this like so: 我会这样解决:
Map<Integer, Integer> countMap = new HashMap<Integer,Integer>();
for( i=0; i<num.length; i++){
int current = input.nextInt();
if(countMap.get(current) != null)
{
int incrementMe = countMap.get(current);
countMap.put(current,++incrementMe);
}
else
{
countMap.put(input.nextInt(),1);
}
}
Try this 尝试这个
The counting method 计数方法
public int count(int[] values, int value)
{
int count = 0;
for (int current : values)
{
if (current == value)
count++;
}
return count;
}
Then use 然后使用
int[] sorted = Arrays.sort(num);
for (int value : sorted)
{
System.out.println("" + value + " occurs " + count(sorted, value) + " times");
}
This works for sure. 这肯定可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.