我正在开发一个项目,我想将 5 个随机数分配给一个数组,然后按升序对这些数字进行排序,但出现以下错误......我将不胜感激。
import java.util.Scanner;
public class YahtzeeGame {
public static Scanner sc = new Scanner(System.in);
// random = random between 1.0 and (6 * .999) + 1 is forced to be integer 1-6
public static int random = (int) (Math.random() * 6 + 1);
public static int[] dice = new int[4];
public static void main (String[] args) {
System.out.println("welcome to Yahtzee!");
roll(dice);
}public static void roll (int[] dice) {
for (int i = 0; i < dice.length; i++) {
dice[i] = random;
sort(dice);
}
} public static void sort(int[] dice) {
int temp;
for (int j = 0; j < dice.length - 1; j++) {
for (int i = 1; i < dice.length - j; i++) {
if( dice[i] > dice[i+1]) {
temp = dice[i-1];
dice[i-1] = dice[i];
dice[i] = temp;
}
}
}
}
}
最佳答案
何时 j = 0
,循环for (int i = 1; i < dice.length - j; i++)
运行至 dice.length - 1
。所以,您正在访问dice[dice.length]
在if( dice[i] > dice[i+1])
这会引发异常。
关于java - 线程中的异常 "main"java.lang.ArrayIndexOutOfBoundsException : 4 Error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41455732/