简体   繁体   English

ArrayIndexOutOfBoundsException:不明白为什么

[英]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. 我不明白为什么在我的createSquad方法的for循环期间填充数组元素时数组出现问题。 It's not letting me pass the array into the createSquad method.. why? 这不是让我将数组传递给createSquad方法..为什么呢? I've tried everything from reformatting the x in the createSquad method to an integer but I still don't get anywhere. 我已经尝试了所有方法,从将createSquad方法中的x重新格式化为整数,但是我仍然createSquad

Your for loop for (int x = 0; x <= squad.length; x++) should be changed to for (int x = 0; x < squad.length; x++) for (int x = 0; x <= squad.length; x++) for循环应更改为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 . Java中基于数组或基于0的数组,因此当x = 3且数组的大小为3时,您将获得ArrayIndexOutOfBoundsException

Try using a debugger in your IDE. 尝试在IDE中使用调试器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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