recckon
recckon

Reputation: 23

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 Error

I am working on a project in which I want to assign 5 random numbers to an array and then sort those numbers in ascending order, but I get the following errors.... I would appreciate any help.

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;
            }
        }
    }  
}
}

Upvotes: 2

Views: 542

Answers (2)

MuTiny
MuTiny

Reputation: 257

I had alter your code hope this helps! I used Arraylist to store your dice values and Make arraylist sort it accordingly.

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();
    }

}

Upvotes: 0

Shakhar
Shakhar

Reputation: 442

When j = 0, the loop for (int i = 1; i < dice.length - j; i++) runs up to dice.length - 1. So, you are accessing dice[dice.length] in if( dice[i] > dice[i+1]) and that throws the exception.

Upvotes: 4

Related Questions