我正在一个项目中,我想向一个数组分配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])
,并抛出异常。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句