简体   繁体   中英

I would like to do printFrequency method in java

I would like to create a method called printFrequency that adds up, and prints, the total number of occurrences of each possible value (0, 1, ..., 9) for my code.

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() {

    }
}

I would like the output for the printFrequency method to be like this:

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

I don't know exactly how to start with it and what loop to use for it or if there is easier way to do it.

I would like to create a method called printFrequency that adds up, and prints, the total number of occurrences of each possible value (0, 1, ..., 9)

Assuming that you want to calculate the frequencies of the number present in the array , here is one solution using a fixed length array which acts as a count bucket for each of the numbers through 0 - 9.

Here is the code snippet:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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