首页 > 解决方案 > 在 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)

标签: javaarrays

解决方案


看起来 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();
        }
    }

推荐阅读