通过 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;
}
最佳答案
首先,星星应该在变化吧?然后
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++) {
不是值.长度
关于java - 从数组值制作非图形直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3081288/