循环骰子模拟

时间:2018-11-09 03:17:55

标签: java

我似乎在循环骰子模拟器时遇到一些麻烦。我已经将代码的主体放置在do-while循环中,但是当输出打印到控制台时,它会添加上次模拟的前一个输出。我曾尝试在几个不同的地方初始化我的“ n”变量,但是没有运气。任何帮助将不胜感激。

我的代码如下...

import java.util.Random;
import java.util.Scanner; 

public class Trash{

   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 again; 
    String stars = ""; 
    double percentage; 


    do{
    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\t\tHistogram\n");
    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\t%1.50s\n",i,frequency[i], percentage, stars);
         }
    System.out.println("Run simulation again?"); 
    String answer = scan.nextLine(); 
    again = answer.toLowerCase();  
    } while (again.equals("yes")); 


}
}

1 个答案:

答案 0 :(得分:0)

原因是因为您在重新启动仿真时没有重新初始化数组。

do {
    // re-initialize here
    frequency = new int [13];
    rolls = new int [13];

    System.out.println("Enter the number of trials:");

    // the rest of your code
} while (again.equals("yes"));