java - 需要帮助打印双骰子滚动程序的直方图

标签 java

我已经查看了以前的问题,并且真的试图弄清楚这一点。我觉得来这里很脏,因为是的,这是作业,但我也试图联系我的教授。过去两周没有回复。我确信这是一个简单的修复,我只是没有得到它,但该死的我已经做了一段时间并且被卡住了。提前谢谢你。

我似乎无法在总计的右侧打印星号。每个“*”代表总卷数的 1%。我想我拥有一切,但我一直无法弄清楚如何在右侧打印它们。

所以代替;

2:****
3:******
4:**

等..

我明白了;

****2:
**3:
*****4:

等..

这是我的代码:

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

    public class DoubleDiceRoll
    {
    public static void main(String[] args)
    {
  Random r = new Random();
  Scanner in = new Scanner (System.in);


  int[] frequency = new int[13];//Recording the number of times a number was rolled
  int numRolls = 0;//How many rolls the user wants to simulate
  int numAsterisks = 0; 
  int dieOne = 0;//Roll of die one
  int dieTwo = 0;//Roll of die two
  int rollTotal = 0;//Sum of the rolls of die one and two
  String stars = ""; 

  //Welcom user to the program
  System.out.println("Welcome to the dice throwing simulator!");

  System.out.println(" ");

  System.out.println("How many dice rolls would you like to simulate?");
  numRolls = in.nextInt();

  //Simulate the number of rolls for die 1 and 2

  for(int i = 0; i < numRolls; i++)
  {

     //Roll dieOne
     dieOne = r.nextInt(6) +1;

     //Roll dieTwo
     dieTwo = r.nextInt(6) +1;

     rollTotal = dieOne + dieTwo; 

     frequency[rollTotal]++;

  }//end for

  //Print Results

  System.out.println("DICE ROLLING SIMULATION RESULTS" + "\n" + "Each \"*\" represents 1% of the total number of rolls." + "\n"
                          + "Total number of rolls: " + numRolls);

  System.out.println("");//Space between text and results                       

  //Create for loop for print statement
  for(int total = 2; total < frequency.length; total++)
  {  
     numAsterisks = 100 * frequency[total] / numRolls; 


     for(int j = 0; j < numAsterisks; j++)
     {
         System.out.println("*");
     }
     System.out.println(total + ": ");
  }


   }


}

我知道我已将 * 设置为在总数之前打印,但我尝试以其他方式打印它似乎更加困惑。我已将 * 设置为等于一个字符串,例如:

for(int j = 0; j < numAsterisks; j++)
 {
   stars += "*";
 }
System.out.print (total + stars);

但是 * 与正确的百分比不匹配,最终打印出随机数量的星号。

最佳答案

像这样尝试:

  System.out.print(total + ": ");
  for(int j = 0; j < numAsterisks; j++)
  {
         System.out.print("*");
  }
  System.out.println("");

打印完 *s 后打印下一行

关于java - 需要帮助打印双骰子滚动程序的直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52809708/

相关文章:

java - 如何将字符串参数传递给使用 Apache Commons Exec 启动的可执行文件?

java - java servlet 中的 session

java - memcached 中的数据结构库

java代码扩展每列以适合文本(自动调整功能)

java - 使用 JSoup 解析后如何将完整的 HTML 表存储在 JTable 中?

java - 将 HashMap 键与文本文件中的单词进行比较并更新值

java - 请求方法 'GET' 不受支持,但它实际上存在于 Controller 中

java - 使用 Intent 向多个联系人发送消息

java - System.out.println 打印字符串,但 System.out.print 不打印

java - 如何使用嵌套的 if 语句而不是 System.exit(0); 来阻止程序在蓝图类中运行?