掷骰子程序

时间:2018-11-07 22:05:24

标签: java drjava

此处是编程的新手。我正在从事即将完成的骰子模拟器项目,但无法添加打印与频率相等的星号的直方图。我相信我需要使用嵌套的for循环,但对我创建的for循环感到非常困惑。第一个结果似乎总是正确的,但其他结果却并非如此。任何帮助将不胜感激。

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);
    }
}
}

1 个答案:

答案 0 :(得分:1)

您只是忘记重置stars变量,然后再对计数

进行计数
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);
}

另外%6d应该是%9d,因为频率是9个长度