【发布时间】: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>(turn.length-2)你的循环条件看看你是否将<与>交换了 -
您正在尝试将
turn[0]打印到turn[5]- 这是您的五元素数组的六个元素。没有turn[5]。