ow to create a histogram in java

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.

Leave a Comment