有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java滚动骰子程序

这里是编程新手。我正在进行骰子模拟器项目,该项目即将完成,但我在添加一个直方图时遇到了问题,该直方图会打印一个与频率相等的星号。我相信我需要使用嵌套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) 个答案

  1. # 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长度