简体   繁体   中英

ArrayIndexOutOfBoundsException: don't understand why

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)

I don't understand why my array is coming to a problem when filling in the array elements during the for loop in my createSquad method. It's not letting me pass the array into the createSquad method.. why? I've tried everything from reformatting the x in the createSquad method to an integer but I still don't get anywhere.

Your for loop for (int x = 0; x <= squad.length; x++) should be changed to for (int x = 0; x < squad.length; x++)

Arrays or 0-based in Java so you when x = 3 and the array is of size 3 you get an ArrayIndexOutOfBoundsException .

Try using a debugger in your IDE.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM