Trying to make a histogram, but the loop I'm trying to use for it is giving me a Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 14 error. I'm trying to get something along the lines of:
* *
* * * *
* * * * * *
* * * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
- - - - - - - - - -
0 1 2 3 4 5 6 7 8 9
And this is what I have so far:
public static void VerticalHist()
{
int max = 0; // initialize max
int[] count = new int[10]; // make array to find max
for (int i = 0; i < 100; i++)
{
int rand = (int)(Math.random() * ((9 - 0) + 1)); // generate random values
count[rand]++;
}
for (int x : count) // find max
{
if (x > max)
max = x;
}
// System.out.println(max);
String[][] nums2 = new String[max][10]; // create 2d array for histogram
for (int x = max; x > 0; x--)
{
System.out.println();
for (int i = 0; i < nums2[x].length; i++)
{
if (count[i] > 0)
nums2[x][i] = "*";
}
}
for (int i = 0; i < max; i++) // print 2d array
{
System.out.println();
for (String n: nums2[i])
{
System.out.print(n);
}
}
}
My loop for inserting the * is giving me the error.
for (int x = max; x > 0; x--)
{
System.out.println();
for (int i = 0; i < nums2[x].length; i++)
{
if (count[i] > 0)
nums2[x][i] = "*";
count[i]--;
else
nums2[x][i] = "";
}
}
I'm trying to take each row, check each index to see if there needs to be an asterisk, (if so, put an asterisk, if not put a blank space) and do so for each row in the 2d array.