Aramza Aramza - 26 days ago 8
Java Question

Java: Looping through and printing based on rounding

I am having trouble figuring out how display a rounded number of asterisks based on their corresponding (numbers on the right of the output) count.

I am attempting to use 1 asterisk to represent 100 asterisks. However, when I get a number such as roll #17 being 417, I want it to print only 4 asterisks, not five; same for rounding up. I tried using Math.round() but I was unsuccessful.

I'd really appreciate any help.

My code:

public class Histogram {

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

int numRoles = 30000;
int[] amountRoles = new int[19]; // amountRoles Holds the Array

for (int i = 3; i < 7; i++)
amountRoles[i] = 0; // Set 0
{
for (int i = 0; i < numRoles; i++)
{
int die1 = (int)(Math.random()*6+1);
int die2 = (int)(Math.random()*6+1);
int die3 = (int)(Math.random()*6+1);
amountRoles[die1+die2+die3]++; // Increments
}
System.out.print("The die was rolled " + numRoles + " times, its six value's counts are:");
for (int i = 3; i < 7; i++)
{
System.out.println(); // Line Holder
}
}
for (int i = 3; i < amountRoles.length; i++) // Iterates through amountRoles
{
System.out.print("[" + i + "]" + " ");
for(int j = 0; j < amountRoles[i]; j++) // Loop through amountRoles[i]
{
if (Math.round(j) % 100 == 0)
{
System.out.print("" + "*");
}
}
System.out.println(" " + amountRoles[i]);
}
}
}


My output:

[3] ** 139
[4] **** 389
[5] ********* 826
[6] ************** 1366
[7] ********************* 2082
[8] ****************************** 2973
[9] *********************************** 3440
[10] *************************************** 3859
[11] ************************************** 3742
[12] *********************************** 3482
[13] ****************************** 2918
[14] ******************** 1996
[15] ************** 1341
[16] ********* 865
[17] ***** 417
[18] ** 165

Answer

Here is the part where you print each line:

System.out.print("[" + i + "]" + "  ");
for(int j = 0; j < amountRoles[i]; j++) // Loop through amountRoles[i]
{
    if (Math.round(j) % 100 == 0)
    {
        System.out.print("" + "*");
    }
}
System.out.println(" "  + amountRoles[i]);

You are looping hundreds of times. That is unnecessary and inefficent. Just use division to get the number of *s to print:

System.out.print("[" + i + "]  ");
int starsToPrint = (int) Math.round((double) amountRoles[i] / 100.0);
for (int j = 0; j < starsToPrint; j++) {
    System.out.print("*");
}
System.out.println(" "  + amountRoles[i]);

Just for your information, the reason your original code was broken was because 0 % 100 == 0, so on the first iteration of your inner for loop it would print an extra "*".