blazefirer blazefirer - 28 days ago 13
Java Question

Java histogram, how to add stars to an array

I want to print an amount of stars equal to the number of times a given number 1 through 6 was rolled. Then put this into an array so I can print the given amount of stars in the middle of a

System.out
.
it would look like this [1] ******************* 19

I already have the base code here

import java.util.Random;
public class Program7 {

public static void main(String[] args) {
Random ran = new Random();
int [] timesRolled = new int[7];
for (int i=0;i<100;i++){
int die= ran.nextInt(6)+1;
if (die==1){
timesRolled [1]++;
System.out.print("*");
}
if (die==2){
timesRolled [2]++;
System.out.print("*");
}
if (die==3){
timesRolled [3]++;
System.out.print("*");
}
if (die==4){
timesRolled [4]++;
System.out.print("*");
}
if (die==5){
timesRolled [5]++;
System.out.print("*");
}
if (die==6){
timesRolled [6]++;
System.out.print("*");
}
}
System.out.println("[1]" + "\t" + here is where i want the stars + timesRolled [1]);
System.out.println("[2]" + "\t" + timesRolled [2]);
System.out.println("[3]" + "\t" + timesRolled [3]);
System.out.println("[4]" + "\t" + timesRolled [4]);
System.out.println("[5]" + "\t" + timesRolled [5]);
System.out.println("[6]" + "\t" + timesRolled [6]);
}

}

Answer

Try this,

import java.util.Random;

public class Program7 {

    public static void main(String[] args) {
        Random ran = new Random();
        int[] timesRolled = new int[7];
        for (int i = 0; i < 100; i++) {
            int die = ran.nextInt(6) + 1;
            if (die == 1) {
                timesRolled[1]++;                
            }
            if (die == 2) {
                timesRolled[2]++;               
            }
            if (die == 3) {
                timesRolled[3]++;                
            }
            if (die == 4) {
                timesRolled[4]++;
            }
            if (die == 5) {
                timesRolled[5]++;
            }
            if (die == 6) {
                timesRolled[6]++;
            }
        }
        for (int i = 1; i < timesRolled.length; i++) {
            int j = timesRolled[i];
            String stars = "";
            for (int k = 0; k < j; k++) {
                stars += "*";
            }
            System.out.println("[" + i + "]" + "\t" + stars + " " + timesRolled[i]);
        }
    }
}