【问题标题】:Can't find error in simple dice game在简单的骰子游戏中找不到错误
【发布时间】:2016-01-26 17:58:30
【问题描述】:

我已经编写了这段代码,编译并运行。 该错误告诉我 Array 超出范围,即使我找不到会发生这种超出范围的位置。另外,到目前为止对改进代码有什么建议吗? (我已经编译了以下布尔值,只是为了在以后使用,所以不要介意它们。)

static boolean threeOfAKind;
static boolean fourOfAKind;

public static int[] newTurn()
{
    int[] rolls=new int[5];
    for (int counter=0 ; counter<5 ; counter++)//we throw 5 dices
    {
        rolls[counter]=(int)(Math.random()*6+1);
        if (rolls[counter]>=7){counter--;}
        //Math.random()*6 could give result of 6 or (1*6) so the 1 added could get to 7
    }
    Arrays.sort(rolls); //makes it easier to display and to check for similar values
    return rolls;
}

public static int checkThreeOfAKind(int[] turn)
{
    int ifTrue=0;
    //while doing a 'for' loop, using the counter to 'scan' the array
    for (int counter=0 ; counter>(turn.length-2)&&ifTrue!=1;counter++)//-2 because if 3rd dice doesn't equal 4th, it's impossible to have 3 of a kind with 5 dices
    {
        if (turn[counter]==turn[counter+1]&&turn[counter+1]==turn[counter+2])
        {
            ifTrue=1;
        }
    }
    return ifTrue;
}

public static int checkFourOfAKind(int[] turn)
{
    int ifTrue=0;
    //while doing a 'for' loop, using the counter to 'scan' the array
    for (int counter=0 ; counter>(turn.length-3)&&ifTrue!=1;counter++)//see note 3 of a kind
    {
        if (turn[counter]==turn[counter+1]&&turn[counter+1]==turn[counter+2]&&turn[counter+2]==turn[counter+3])
        {
            ifTrue=1;
        }
    }
    return ifTrue;
}

public static void main(String[] args)
{       
    Scanner input = new Scanner(System.in);
    int[] turn=newTurn();//puts the results of the throw in an array
    if (checkThreeOfAKind(turn)==1){threeOfAKind=true;}
    if (checkFourOfAKind(turn)==1){fourOfAKind=true;}
    System.out.println("Thown dices:\n"+turn[0]+", "+turn[1]+", "+turn[2]+", "+turn[3]+", "+turn[4]+", "+turn[5]);
    if (fourOfAKind=true){System.out.println("Four of a kind!");}
    if (threeOfAKind=true){System.out.println("Three of a kind!");}
    //error originates from above line
    input.close();
}

【问题讨论】:

  • 您使用的是什么 IDE?通常它会告诉你行号,所以你应该知道错误的确切位置
  • eclipse,第 62 行说,这很奇怪,因为fourOfAKind 会在 ThreeofAKind 之前运行,并且没有错误
  • 你能标记那条线吗? a) 我很懒 b) 其他用户的生活可能比计算代码行数更好。
  • counter&gt;(turn.length-2) 你的循环条件看看你是否将&lt;&gt; 交换了
  • 您正在尝试将turn[0] 打印到turn[5] - 这是您的五元素数组的六个元素。没有turn[5]

标签: java arrays for-loop dice


【解决方案1】:

您的函数newTurn() 返回rolls,其定义为

int[] rolls=new int[5];

您在main() 中写道:

int[] turn=newTurn();

所以,turn 现在引用了一个长度为 5 的数组,该数组的索引从 04

但是在

System.out.println("Thown dices:\n"+turn[0]+".... +turn[5]);

您正在尝试访问turn[5],这肯定会导致ArrayIndexOutOfBoundsException

【讨论】:

    猜你喜欢
    • 2020-11-26
    • 2012-02-29
    • 2021-12-14
    • 2015-08-25
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多