java - 在 JAVA 中创建一个直方图,让您可以直观地检查一组值的频率分布
问题描述
package main;
public class Practice {
public static void main(String[] args) {
int array[] = {19, 3, 15, 7, 11, 9, 13, 5, 17, 1};
int base10=0;
for (int j=1; j <=100; j+=10) {
System.out.print(j + " - " + (base10+=10) + " | " );
for (int index = j ; index <= base10 ; index ++) {
while(array[index] > 0) {
System.out.print("*");
array[index]--;
}
}
System.out.println();
}
}
}
我想为 1 到 10、11 到 20 等范围内的每个值显示一个星号 (*)。这是我的代码,但我收到错误!这是输出:
1 - 10 | *******************************************************************
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
at main.Practice.main(Practice.java:25)
解决方案
看起来 array[] 存储了 bar 的长度。你想打印结果如下
1 - 10 | *******************
11 - 20 | ***
21 - 30 | ***************
31 - 40 | *******
41 - 50 | ***********
51 - 60 | *********
61 - 70 | *************
71 - 80 | *****
81 - 90 | *****************
91 - 100 | *
这是我的解决方案代码:
public static void main(String[] args) {
int array[] = {19, 3, 15, 7, 11, 9, 13, 5, 17, 1};
int index = 0;
int base10=0;
for (int j=1; j <=100; j+=10) {
System.out.print(j + " - " + (base10+=10) + " | " );
while(array[index] > 0) {
System.out.print("*");
array[index]--;
}
index++;
System.out.println();
}
}
推荐阅读
- json - 如何通过单击“下一步”按钮切换到其他员工?以及如何在 PageView.builder 之后添加页面?
- mulesoft - RAML 用于多个文件作为输出
- python - python-Dataframe 计算有条件的行
- android - 使用 PdfBox Android 缓慢的页面渲染
- ruby-on-rails - 我可以在我的主页上运行我的#game 控制器的#new 和#create 方法吗?
- javascript - 如何在已经解决后再次使用承诺
- php - PHP_curl 重定向时的内容长度松散
- swift - Alamofire 与 Swift 使用 Get
- iis - 让我们加密不是 SSL 所有页面
- google-apps-script - 有没有办法重用在遍历一列值时将行附加到工作表的逻辑?