我编写了这段代码,编译并运行。 错误告诉我数组越界,即使我找不到这个超出界限的位置。此外,到目前为止,有关改进代码的任何建议? (我编译了以下布尔值只是为了在后期使用,所以不要介意它们。)
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();
}
答案 0 :(得分:2)
您的函数newTurn()
返回rolls
,其定义为
int[] rolls=new int[5];
在你写的main()
中:
int[] turn=newTurn();
因此,turn
现在引用一个长度为5
的数组,该数组的编号从0
到4
。
但是在
System.out.println("Thown dices:\n"+turn[0]+".... +turn[5]);
您正在尝试访问turn[5]
,这肯定会导致ArrayIndexOutOfBoundsException
。