gpt4 book ai didi

java - ArrayIndexOutOfBoundsException : don't understand why

转载 作者:行者123 更新时间:2023-12-02 03:49:00 30 4
gpt4 key购买 nike

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)

我不明白为什么在 createSquad 方法中的 for 循环期间填充数组元素时,我的数组会出现问题。它不允许我将数组传递到 createSquad 方法中。为什么?我已经尝试了各种方法,从将 createSquad 方法中的 x 重新格式化为整数,但仍然一无所获。

最佳答案

你的for循环for (int x = 0; x <= squad.length; x++)应更改为for (int x = 0; x < squad.length; x++)

Java 中的数组或基于 0 的数组,因此当 x = 3 并且数组大小为 3 时,您会得到 ArrayIndexOutOfBoundsException .

尝试在 IDE 中使用调试器。

关于java - ArrayIndexOutOfBoundsException : don't understand why,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36054260/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com