2016-03-17 5 views
0
import java.util.Random; // random class 

public class MartianBattler { // start of class 
    public static void main(String[] args) { // start of main 
     int battles = 0; //initializes battles to 0 
     Random rand = new Random(); // creates an object of random class 

     int[] squad = new int[rand.nextInt(5)+1]; // generates a random number to tell us how many squads we will have  
     battles = rand.nextInt((5)+1); // generates number of battles to fight 
     createSquad(squad); 
     battle(squad, battles); // passes array squads elements to battle static method 
    } // end of main 

    public static void battle(int[] squad, int battle) { // static method that sends troops to battle 
     for(int x = 0; x < battle; x++) { // for loop 
      Random randS = new Random(); // generate random object 
      int first = randS.nextInt(squad.length)+1; // generate first martian to go 
      System.out.printf("%d%n %d%n%d%n", squad.length, first, battle); 
     } 
    } 

    public static void createSquad(int[] squad) { 
     Random ramdS = new Random(); 

     MartianAttack foo = new MartianAttack(0,false); 
     boolean clone = false; 
     for(int x = 0; x <= squad.length; x++) 
     { 
      clone = ramdS.nextBoolean(); 
      if (clone == true) 
       squad[x] = foo.getidNumber(); 
      else 
       squad[x] = ramdS.nextInt((100)+1); 
     } 
    } 
} // end of class 

run: 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 
    at MartianBattler.createSquad(MartianBattler.java:48) 
    at MartianBattler.main(MartianBattler.java:12) 
C:\Users\Ethan\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1 
BUILD FAILED (total time: 0 seconds) 

Я не понимаю, почему мой массив подходит к проблеме при заполнении элементов массива во время for цикла в моем createSquad методе. Это не позволяет мне передать массив в метод createSquad .. почему? Я пробовал все от переформатирования x в методе createSquad до целого числа, но я все равно ничего не получаю.ArrayIndexOutOfBoundsException: не понимает, почему

ответ

2

Ваш цикл for (int x = 0; x <= squad.length; x++) должен быть изменен на for (int x = 0; x < squad.length; x++)

Массивы или 0 на основе в Java, так что вы, когда х = 3 и массив имеет размер 3 вы получаете ArrayIndexOutOfBoundsException.

Попробуйте использовать отладчик в своей среде IDE.

+0

Спасибо, что был ответом! Как-то я забыл, что массив [3] подходит только к массиву [2] при печати или хранении ... СПАСИБО! –

Смежные вопросы