how to create a histogram in java [duplicate]

心已入冬 提交于 2019-11-29 15:30:44
Gennadiy Ryabkin

Here are some various bits of code you can use to accomplish this.

Create array

int[] histogram = new int[13];

Increment a position in the array

histogram[id]++;

Print histogram

System.out.println("Histogram of rolls:" );
printHistogram(histogram);

Here are some helper functions as well.

private void printHistogram(int[] array) {
     for (int range = 0; range < array.length; range++) {
        String label = range + " : ";
        System.out.println(label + convertToStars(array[range]));
    }
}

private String convertToStars(int num) {
    StringBuilder builder = new StringBuilder();
    for (int j = 0; j < num; j++) {
        builder.append('*');
    }
    return builder.toString();
}

Code should be modified as needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!