java - 掷骰子程序

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

最佳答案

您只是忘记在迭代计数之前重置 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 长度

关于java - 掷骰子程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53198583/

相关文章:

java - Clojure java.lang.Exception 错误 : transaction rolled back: d ! = clojure.lang.Keyword (NO_SOURCE_FILE:0)

java - 对齐GXT表格:FieldLabel with its gwt:Label widget

java - (Java)程序在我想输入字符串时忽略扫描仪

java - Android 辅助功能 com.android.settings :id/left_button about force stop not work

java - 一个接一个地播放音乐

java - 为什么我的 for 循环不会停止;尽管有一个 boolean 表达式?

java - 需要帮助更改按钮背景

java - In 无法解析为类型

java - Java while循环不适用于字符的输入检查