线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:4错误

时间:2017-01-04 03:24:05

标签: java

我正在开发一个项目,我想在其中为一个数组分配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;
            }
        }
    }  
}
}

2 个答案:

答案 0 :(得分:4)

j = 0时,循环for (int i = 1; i < dice.length - j; i++)最多运行dice.length - 1。因此,您正在访问dice[dice.length]中的if( dice[i] > dice[i+1])并抛出异常。

答案 1 :(得分:0)

我改变了你的代码希望这有帮助!我使用Arraylist来存储你的骰子值,然后让arraylist对它进行排序。

package activities;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
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 Random rndm = new Random();
    public static int[] dice = new int[5];
    public static ArrayList<Integer> diceNumber = new ArrayList<>(5);

    public static void roll () {
        for (int i = 0; i < dice.length; i++) {
            dice[i] = rndm.nextInt(6) + 1;           
            while(diceNumber.contains(dice[i])){
                dice[i] = rndm.nextInt(6) + 1;
            }
            diceNumber.add(dice[i]);
        }       
        Collections.sort(diceNumber);
        System.out.println("" + diceNumber);
    } 

    public static void main(String[] args) {
        System.out.println("welcome to Yahtzee!");
        roll();
    }

}