2017-01-04 9 views
2

私は配列に5つの乱数を割り当て、昇順で並べ替えるプロジェクトに取り組んでいますが、次のエラーが出ます....私はどんな助けにも感謝します。 j = 0スレッド "main"の例外java.lang.ArrayIndexOutOfBoundsException:4エラー

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

5個の数値を格納するには 'public static int [] dice = new int [5];が必要です。 –

+0

実際のエラーが何であるか貼り付ける必要があります:) – muzzlator

+1

そして、 'roll'の' for'ループの外側に 'sort(dice)'を入れたいとします。 1行下に移動します。 –

答えて

4

dice.length - 1までループfor (int i = 1; i < dice.length - j; i++)実行されます。したがって、if(dice[i] > dice[i+1])dice[dice.length]にアクセスしていて、例外がスローされます。

+0

ありがとう! – recckon

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

} 
関連する問題