【问题标题】:Dice Rolling in BlueJ在 BlueJ 中掷骰子
【发布时间】:2014-10-07 22:33:08
【问题描述】:

我的代码有什么问题?我正在使用 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.");
            }
    }
}   

【问题讨论】:

  • 你告诉我们怎么了!添加异常消息(如果有),以及预期和实际输出。

标签: bluej dice


【解决方案1】:

你的代码行

int[ ] output = new int[c]

应该实际阅读

int[ ] output = new int[d]

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

【讨论】:

    【解决方案2】:
    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");
            }
        }
       }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-08
    • 2012-02-29
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2017-04-09
    相关资源
    最近更新 更多