2

通过 starPrint 方法,我需要使数组中填充的每个数字的频率显示在直方图中,如下所示:

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

等等。它需要填充的星星数量等于数字出现的频率!目前我得到了数组长度的星号数量。

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

3 回答 3

1

这是 Ada 中的一个示例可以为您提供指导。

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;

附录:注意starPrint()总是返回相同数量的星星。每次打印 的值时hist1[i],打印出多少颗星。

附录:考虑更改starPrint(int[] value)starPrint(int value).

于 2010-06-21T00:59:17.097 回答
1

首先,明星应该会改变吧?然后

String star = starPrint(hist1);

应该在这里

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

其次,您的starPrint方法必须从

public static String starPrint(int[] value) {

public static String starPrint(int value) {

这意味着您将需要随机获得的值而不是数组的长度

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

不是 value.length

于 2010-06-21T01:53:33.863 回答
0

您是否考虑过使用Map<Integer, Integer>? 您可以遍历数组,并为每个数字检查它当前是否是地图的键。如果是这样,获取关联的值并增加它。如果没有,请将数字以及到目前为止发生的次数(一)放在地图中。

然后在打印直方图时,只需遍历keySet()地图,并获取值。

于 2010-06-21T01:07:21.610 回答