蓝色骰子滚动

时间:2014-08-14 09:58:22

标签: bluej dice

我的代码出了什么问题?我正在使用 BlueJ 。基本上我要做的就是,选择骰子的边数,输入每个边的数量,掷骰子一定次数,并显示数字滚动的次数。

示例:六面,数字为:1,2,3,4,5,6。我掷骰子20次。而且我看到一侧被翻了多少次。

错误是java.lang.ArrayIndexOutOfBoundsException

import javax.swing.*;
class Dice
{
    public static void main (String [] args)
    {
            int c = Integer.parseInt(JOptionPane.showInputDialog("How many sides?"));
            String[ ] number = new String[c];
            int[ ] sides = new int[c];

            int d = Integer.parseInt(JOptionPane.showInputDialog("How many times do you want to roll your dice?"));
            int[ ] output = new int[c];

            for(int i=0;i<c;i++)
            {
                number[i] = JOptionPane.showInputDialog("Enter side number:");
            }
            for(int i=0;i<d;i++)
            {
                int r;
                r = (int) Math.floor(Math.random() * c) + 1;

                if(r == sides[i])
                {
                    sides[i] = sides[i] + 1;
                }
            }
            for(int i=0;i<c;i++)
            {
                System.out.println(number[i] + " was rolled " + output[i] + " times.");
            }
    }
}   

2 个答案:

答案 0 :(得分:1)

您的代码行

int[ ] output = new int[c]

实际应该阅读

int[ ] output = new int[d]

因为输出数组的大小应该等于用户想要滚动存储在d中的die的次数。 c存储模具上的边数。

答案 1 :(得分:-1)

import javax.swing.*;
class Dice
{
public static void main (String [] args)
{
        int c = Integer.parseInt(JOptionPane.showInputDialog("How many sides?"));
        String[ ] number = new String[c];


        int d = Integer.parseInt(JOptionPane.showInputDialog("How many times do you 
     want to roll your dice?"));
        int[ ] output = new int[c];

        for(int i=0;i<c;i++)
        {
            number[i] = JOptionPane.showInputDialog("Enter side number:");
        }
        for(int i=0;i<d;i++)
        {
            System.out.println("exoashf");
            int r;
            r = (int) Math.floor(Math.random() * c) + 1;
            for(int j=0;j<d;i++)
            {
                int n1=Integer.parseInt(number[j]);
                if(r==n1)
                {
                    output[j]=output[j]+1;
                }
            }
        }
        for(int i=0;i<c;i++)
        {
            System.out.println("number, "+number[i]+"was rolled "+output[i]+"times");
        }
    }
   }