我想在java中做printFrequency方法

时间:2016-03-24 06:47:06

标签: java

我想创建一个名为import java.util.Random; public class Array { int[] array; int size = 0; public Array(int s) { size = s; array = new int[size]; } public void print() { for (int i = 0; i < size; i++) System.out.printf("%d,", array[i]); System.out.println(); } public void fill() { Random rand = new Random(); for (int i = 0; i < size; i++) array[i] = rand.nextInt(10); } public void sort() { for (int i = 0; i < size; i++) { int tmp = array[i]; int j = i; for (; j > 0 && (tmp < array[j - 1]); j--) array[j] = array[j - 1]; array[j] = tmp; } } public void printFrequency() { } } 的方法,它为我的代码添加并打印每个可能值(0,1,...,9)的总出现次数。

printFrequency

我希望Frequencies: There are 2, 0's There are 0, 1's There are 0, 2's There are 0, 3's There are 3, 4's There are 0, 5's There are 2, 6's There are 1, 7's There are 0, 8's There are 2, 9's 方法的输出如下:

mvn org.apache.maven.plugins:maven-dependency-plugin:2.10:copy -Dartifact=com.uhg.optum.acc:cores-binaries:%PLATFORM_CORE_VERSION% -DoutputDirectory=. -Dmdep.useBaseVersion=true

我不知道如何开始使用它以及使用它的循环方式,或者是否有更简单的方法。

1 个答案:

答案 0 :(得分:0)

  

我想创建一个名为printFrequency的方法,它可以累加并打印每个可能值(0,1,...,9)的出现次数

假设您要计算array中存在的数字的频率,这里有一个使用固定长度数组的解决方案,该数组充当每个数字到0到9的计数桶。

以下是代码段:

private static void printFrequency() {
    int[] countArray = new int[10];
    for(int x : array) {
        countArray[x]++;
    }

    System.out.print("Frequencies: ");
    for(int i = 0; i < 10; i++) {
        System.out.print("There are " + countArray[i] + ", " + i + "'s ");
    }
}