Aramza Aramza - 25 days ago 14
Java Question

Java: Array asterisk printing for values

I am trying to print asterisks based on the number of times a dices side is rolled (all through an array). I am coming across an issue with the printing of the dice side (i) before the asterisks. Also, I'm getting two zeroes out of nowhere and don't know where they're coming from.
I'd appreciate the help.

My code:

public class Histogram {

public static void main(String[] args) {
// TODO Auto-generated method stub

int numRoles = 100;
int[] amountRoles = new int[7]; // amountRoles Holds the array

for (int i = 1; i < 7; i++)
amountRoles[i] = 0; // Set 0
{
for (int i = 0; i < numRoles; i++)
{
int die1 = (int)(Math.random()*6+1);
amountRoles[die1]++; // Increments
}
System.out.println("The die was rolled " + numRoles + " times, its six value's counts are:");
for (int i = 1; i < 7; i++)
{
System.out.print("Side " + i + " was rolled " + amountRoles[i]+ " times out of " + numRoles + ".");
// Prints each sides value (i) alongside with how many times it was rolled (amountRoles[i]).
System.out.println(); // Formatting Line
}
}
for (int i = 0; i < amountRoles.length; i++) // Iterates through amountRoles
{
for(int j = 0; j < amountRoles[i]; j++) // Loop through amountRoles[i]
{
System.out.print("" + "*");
}
System.out.println(i + " " + amountRoles[i]);
}
}
}


My output:

The die was rolled 100 times, its six value's counts are:
Side 1 was rolled 11 times out of 100.
Side 2 was rolled 19 times out of 100.
Side 3 was rolled 19 times out of 100.
Side 4 was rolled 17 times out of 100.
Side 5 was rolled 16 times out of 100.
Side 6 was rolled 18 times out of 100.
0 0 (Where are these zeroes coming from?)
***********1 11
*******************2 19
*******************3 19
*****************4 17
****************5 16
******************6 18


An example output I am aiming for:

[1] ******************* 19
[2] ************ 12
[3] ********************* 21
[4] ******************** 20
[5] ************* 13
[6] *************** 15

Answer

Only answering your question an no other problems I see with the code, you are getting the 0 0 from int i = 0. Change this to int i = 1 and no more 0 0!

To get your values to print the way you need, you just need to simple move what you want to print before the * above the loop. In this case [i], and move the amount each roll was below the * loop. Code is below. This should fix your stated problems.

for (int i = 1; i < amountRoles.length; i++) // Iterates through amountRoles
{
    System.out.print("[" + i + "]");
    for(int j = 0; j < amountRoles[i]; j++) // Loop through amountRoles[i]
    {
        System.out.print("" + "*");
    }
    System.out.println(" " + amountRoles[i]);
}
Comments