How to Display a Vertical Histogram in Java
The Java programming language, at its core, contains the basic data types and functionality to build many different data structures and representations. For example, the histogram is a representation of data occurrence within a range of values. While Java contains an advanced class to build histograms from image data, you can also create a basic histogram using any range of data. By using multidimensional arrays and some strategic "for" loops, you can print a basic histogram to the user's console.
Instructions
-
-
1
Create your basic class:
class BasicHistogram{
}
-
2
Declare the histogram variable inside the class definition. The "graph" array represents the histogram itself. The "count" array represents the value occurrences for each column in the histogram. The "symbol" variable represents the symbol to display in the histogram:
class BasicHistogram{
public static String line = "--------------------";
public static String symbol = "x";
public static String[][] graph = new String[10][10];
public static int[] count = new int[10]; -
-
3
Declare the main method of the class:
class Histo{
public static String line = "--------------------";
public static String symbol = "x";
public static String[][] graph = new String[10][10];
public static int[] count = new int[10];public static void main(String[] args){
-
4
Inside the main method, populate the count array with values:
public static void main(String[] args){
for (int i = 0; i < 10; i++){
count[i] = i;
}count[5] = 7;
count[2] = 8;
count[9] = 1; -
5
Populate the histogram array with symbols, based on the values in the count array:
for (int j = 0; j < 10; j++){
for (int i = 0; i < count[j]; i++){
graph[j][i] = symbol;
}
} -
6
Print the histogram to the screen:
for (int l = 9; l >= 0; l--){
for (int k = 0; k < 10; k++){
if (graph[k][l] == symbol){
System.out.print(graph[k][l]);}else{
System.out.print(" ");
}
}
System.out.print("\n");
}
System.out.println(line);
-
1