线程“main”java.lang.arrayindexoutofboundsexception中出现异常:4错误

uxhixvfz  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(490)

我在做一个项目,我想给一个数组分配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;
            }
        }
    }  
}
}
31moq8wy

31moq8wy1#

什么时候 j = 0 ,循环 for (int i = 1; i < dice.length - j; i++) 运行到 dice.length - 1 . 所以,你正在访问 dice[dice.length]if( dice[i] > dice[i+1]) 这就抛出了一个例外。

xzv2uavs

xzv2uavs2#

我已经修改了你的代码希望这有帮助!我使用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();
    }

}

相关问题