开发者

Making non-graphical Histogram from array values

Via the starPrint method I need to make the frequency of each number populated in the array display in a histogram as such:

1=3***
2=4****
3=7*******

and so on. It needs the number of stars populated that are equal to the frequency of the number appearing! At the moment I'm getting the number of asterisks of the length of the array.

public static void main(String[] args) {

    int matrix[][] = new int[100][2];

    for (int row = 0; row < matrix.length; row++) {
        for (int column = 0; column < matrix[row].length; column++) {
            matrix[row][column] = (int) (Math.random() * 6 + 1);
        }

    }
    int[] hist1 = frequency(matrix);

    String star = starPrint(hist1);
    for (int i = 1; i < hist1.length; i++) {
        System.out.print(" \n" + hist1[i] + star);
    }

}

public static String starPrint(int[] value) {

    String star = 开发者_如何学编程"";
    for (int i = 0; i < value.length; i++) {

        star += "*";
    }
    return star;
}

public static int[] frequency(int[][] matrix) {

    int[] nums = new int[7];

    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            nums[matrix[i][j]] += 1;
        }
    }
    return nums;
}


First thing, stars should be changing right ? then

String star = starPrint(hist1);

should be within here

for (int i = 1; i < hist1.length; i++) {
        System.out.print(" \n" + hist1[i] + star);
}

Second your starPrint method will have to change (unless that is how method is stated in the homework ???) from

public static String starPrint(int[] value) {

to

public static String starPrint(int value) {

which means that you will need the value that you got at random and not the length of the array

for (int i = 0; i < value; i++) { 

Not value.length


Here's an example in Ada that may guide you.

Max_Count  : constant Integer := 1_200;
Bin_Size   : constant Integer := 100;
--
type Histogram is array (0 .. Max_Count / Bin_Size - 1) of Integer;
Graph : Histogram := (others => 0);
--
for J in Graph'Range loop --'
   TIO.Put(Label(J));
   for K in 1 .. (Graph(J) * Plot_Size) / Game_Count loop
      TIO.Put("*");
   end loop;
   TIO.New_Line;
end loop;

Addendum: Note that starPrint() always returns the same number of stars. Each time you print the value of hist1[i], print out that many stars.

Addendum: Consider changing starPrint(int[] value) to starPrint(int value).


Have you considered using a Map<Integer, Integer>? You could iterate through the array, and for each number check to see if it was currently a key for the map. If so, get the associated value and increment it. If not, put the number in the map, along with the number of times it has occurred so far (one).

Then when it come to printing the histogram, just iterate through the keySet() of the map, and get the values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜