【问题标题】:Rolling dice program掷骰子计划
【发布时间】:2018-11-07 22:05:23
【问题描述】:

这里是编程新手。我正在处理几乎完成的骰子模拟器项目,但我无法添加一个打印与频率等效的星号的直方图。我相信我需要使用嵌套的 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);
    }
}
}

【问题讨论】:

  • 请给出您的输出,以及与预期输出的差异

标签: java drjava


【解决方案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 长度

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-08
    • 2021-08-19
    • 2012-02-29
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    相关资源
    最近更新 更多