繁体   English   中英

排序数组并计算其元素

[英]sorting an array and counting its elements

我试图对数组进行排序并计算数组元素,请帮助我查找缺少的内容,已调试了很多次。 这是我的代码和我得到的输出。 谢谢

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++;
        }

在这里调用函数

        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);
    }
}

这是输出:

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

您的问题是该数组的大小为30,并且在对它进行排序时,您没有分配的所有值都等于0,因此它们位于已排序数组的前面。 之后的前6个数字全为0,因此输出正确。

为了避免您遇到的问题,我建议您使用ArrayList而不是简单数组,以便可以向其中动态添加元素。

您所做的工作比必要的多。 我会这样解决:

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);  
     }  
}

尝试这个

计数方法

public int count(int[] values, int value)
{
    int count = 0;
    for (int current : values)
    {
        if (current == value)
            count++;
    }
    return count;
}

然后使用

int[] sorted = Arrays.sort(num);
for (int value : sorted)
{
    System.out.println("" + value + " occurs " + count(sorted, value) + " times");
}

这肯定可以工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM