直方图中显示的骰子概率

时间:2015-12-15 01:03:12

标签: java arrays

These are the first 14 steps我想我应该设定限制。

对于作业我被要求为此输出编写代码:

你想要多少骰子? (1至3)

3

每个骰子有多少面? (从2-9中选择一个选项)

9

多少卷? (选择1000 - 20亿)

亿

Histogram

继续? (“是”表示“是”,“假”表示“否”):真实

到目前为止,我有这个:

boolean go =true; 
do {
    System.out.println("How many dice do you want? (1 to 3)");
    int dicenum = scan.nextInt();
    System.out.println("How many sides does each die have? (Choose an option from 2-9)");
    int sidenum = scan.nextInt();
    System.out.println("How many rolls? (Choose from 1000 - 2 billion)");
    int rollnum = scan.nextInt();
    int a =0;
    while (a<=rollnum){
        int [] result = new int [rollnum];
        result[a] = rand.nextInt(sidenum) + 1;

    a++;
    }
    System.out.print("Continue? (\"true\" for yes and \"false\" for no): ");
    again = scan.nextBoolean();
    if (again==false){
        go=false;
    }
    System.out.println('\n');
}while (go);

我不确定如何在内循环中合并骰子的数量,并且代码代表我得到这个错误:

你想要多少骰子? (1至3)

2

每个骰子有多少面? (从2-9中选择一个选项) 3

多少卷? (选择1000 - 20亿)

1000

线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:1000     在project2.HistogramCLI.main(HistogramCLI.java:124)

1 个答案:

答案 0 :(得分:0)

你得到一个IndexOutOfBoundsException,因为你的结果数组中的最后一个元素是rollnum - 1,但是你现在有了while循环的方式,直到结果[rollnum],这就是抛出异常的原因。 / p>

至于在内循环中加入骰子的数量,我需要知道该程序的主要目标是什么才能帮助你完成该部分。

编辑:如果你想制作一个像你链接的直方图,那么只需在你的do循环中创建两个for循环。从dicenum迭代到(dicenum * sidenum)/ 2,按升序为每个总滚动值打印出适当数量的星号。然后对于第二个,从((dicenum * sidenum)/ 2)+ 1到(dicenum * sidenum)做同样的事情,但是按升序。