Reputation: 89
new to programming here. I am working on dice simulator project that is almost finished but I am having trouble adding a histogram that prints an asterisk equivalent to the frequency. I believe i need to use nested for loops but am getting very confused with the for loops i have created.The first outcome always seems to be correct but the rest are not. Any help would be greatly appreciated.
import java.util.Random;
import java.util.Scanner;
public class RollingDice{
public static int getInt(Scanner scan) {
int input;
while ( !scan.hasNextInt() ) {
String garbage = scan.nextLine();
System.out.println("Please enter an integer. ");
}
input = scan.nextInt();
scan.nextLine();
return input;
}
public static void main(String [] args){
Scanner scan = new Scanner(System.in);
Random rand = new Random();
int dice1, dice2;
int [] frequency = new int [13];
int [] rolls = new int [13];
String stars = "";
double percentage;
System.out.println("Enter the number of trials:");
int n = getInt(scan);
for (int i = 0; i < n; i++) {
dice1 = rand.nextInt(6)+1;
dice2 = rand.nextInt(6)+1;
frequency[dice1+dice2]++;
}
System.out.printf("Outcome\tFrequency\tPercentage\tHistogram\n");
for (int i = 2; i < frequency.length; i++) {
for ( int j = 0; j < frequency[i]; j++) {
stars = stars + "*";
}
percentage = (frequency[i] * 100.0) / n;
System.out.printf("%7d\t%6d\t%10.2f\t%s\n",i,frequency[i], percentage, stars);
}
}
}
Upvotes: 0
Views: 66
Reputation: 54148
You just forgot to reset the stars
variable before iterate on the counting :
for (int i = 2; i < frequency.length; i++) {
stars = "";
for ( int j = 0; j < frequency[i]; j++) {
stars = stars + "*";
}
percentage = (frequency[i] * 100.0) / n;
System.out.printf("%7d\t%9d\t%10.2f\t%s\n",i,frequency[i], percentage, stars);
}
Also %6d
should be %9d
as Frequency is 9-length
Upvotes: 1