从数组值制作非图形直方图
通过 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,明星应该会改变吧?那么
应该在这里
第二个你的
starPrint
方法将不得不改变(除非这是家庭作业中所述的方法???)从 到这
意味着你将需要随机获得的值而不是数组的长度
Not value.length
First thing, stars should be changing right ? then
should be within here
Second your
starPrint
method will have to change (unless that is how method is stated in the homework ???) fromto
which means that you will need the value that you got at random and not the length of the array
Not value.length
这是 示例。 org/wiki/Ada_%28programming_language%29" rel="nofollow noreferrer">Ada 可能会指导您。
附录:请注意,
starPrint()
始终返回相同数量的星星。每次打印hist1[i]
的值时,都会打印出那么多的星星。附录:考虑将
starPrint(int[] value)
更改为starPrint(int value)
。Here's an example in Ada that may guide you.
Addendum: Note that
starPrint()
always returns the same number of stars. Each time you print the value ofhist1[i]
, print out that many stars.Addendum: Consider changing
starPrint(int[] value)
tostarPrint(int value)
.您是否考虑过使用
Map
?您可以迭代该数组,并针对每个数字检查它当前是否是地图的键。如果是,则获取关联值并递增它。如果没有,请将数字以及迄今为止发生的次数(一)放入地图中。然后,在打印直方图时,只需迭代地图的
keySet()
即可获取值。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.