在阵列中查找不同数字的方法及其频率

时间:2017-03-17 20:57:20

标签: java arrays methods frequency

帮助我找到此代码中的错误,我不明白为什么它不起作用。我想显示数组中的所有唯一数字,以及它们的频率(它们出现的次数)。

package myProj;

import java.util.Scanner;

public class Freq {

    static boolean isRepeated(int[] temp,int zz){
         int flag=0;
         int l=java.util.Arrays.asList(temp).indexOf(zz);
         for(int p=0;p<l;p++){
            if(temp[p]==zz){
                flag=flag+1;
            }
         }
         if(flag==0){
             return false;
             }
         else{
             return true;
             }
     }

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("enter the no of array elements");
        int numOfNumbers = sc.nextInt();

        int arrayOfNumbers[] = new int[numOfNumbers];
        for (int i = 0; i < numOfNumbers; i++) {
            System.out.print("Enter the number:");
            arrayOfNumbers[i] =sc.nextInt();
        }

        for(int i = 0; i<numOfNumbers; i++){
            int z=arrayOfNumbers[i];
            if(!(isRepeated(arrayOfNumbers,z))){
                int count=0;
                for(int j=0;j<numOfNumbers;j++){

                    if(arrayOfNumbers[j]==arrayOfNumbers[i]){
                        count=count+1;
                    }
                    else{
                        continue;
                    }
                }
                System.out.println("Frequency of "+arrayOfNumbers[i]+"is"+count);
            }
            else{
                continue;
            }
        }
    }
}

[2,20,11,10,5,14,47,23,20,12,11,10]的预期输出示例

  • 频率2:1频率20:2频率11:2频率 10:2频率为5:1频率为14:1频率为47:1 频率为23:1频率为12:1

请帮助纠正我的代码,而不是提出新的逻辑。

1 个答案:

答案 0 :(得分:0)

你可以让它变得更容易:

public class Freq {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the no of array elements");
        int numOfNumbers = sc.nextInt();

        Integer[] arrayOfNumbers = new Integer[numOfNumbers];
        for (int i = 0; i < numOfNumbers; i++) {
            System.out.print("Enter the number:");
            arrayOfNumbers[i] = sc.nextInt();
        }

        // to remember for what numbers we already count freq
        List<Integer> tmpList = new ArrayList<>(numOfNumbers);

        for (Integer number : arrayOfNumbers) {
            if (!tmpList.contains(number)) {
                tmpList.add(number);
                System.out.println("Frequency of " + number + " is " + Collections.frequency(Arrays.asList(arrayOfNumbers), number));
            }
        }
    }
}