阵列索引边界外异常:don';我不明白为什么 import java.util.Random;//随机类 公开课火星战士{//开始上课 公共静态void main(字符串[]args){//main的开始 int battles=0;//将战斗初始化为0 Random rand=new Random();//创建Random类的对象 int[]squad=new int[rand.nextInt(5)+1];//生成一个随机数,告诉我们将有多少个小队 battles=rand.nextInt((5)+1);//生成要战斗的战斗数 小队(小队),; 战斗(小队,战斗);//将阵列小队元素传递给战斗静态方法 }//主管道末端 公共静态无效战斗(int[]小队,int战斗){//派遣部队作战的静态方法 for(intx=0;x
Your for loop阵列索引边界外异常:don';我不明白为什么 import java.util.Random;//随机类 公开课火星战士{//开始上课 公共静态void main(字符串[]args){//main的开始 int battles=0;//将战斗初始化为0 Random rand=new Random();//创建Random类的对象 int[]squad=new int[rand.nextInt(5)+1];//生成一个随机数,告诉我们将有多少个小队 battles=rand.nextInt((5)+1);//生成要战斗的战斗数 小队(小队),; 战斗(小队,战斗);//将阵列小队元素传递给战斗静态方法 }//主管道末端 公共静态无效战斗(int[]小队,int战斗){//派遣部队作战的静态方法 for(intx=0;x,java,arrays,indexoutofboundsexception,Java,Arrays,Indexoutofboundsexception,Your for loopfor(int x=0;xYour for loopfor(int x=0;x)谢谢这是答案!不知怎的,我忘了数组[3]在打印或存储时只升到数组[2]……谢谢!谢谢这是答案!不知怎的,我忘了数组[3]在打印或存储时只升到数组[2]……谢谢! import java.util.Random; // random class public class MartianBattler { // start of class public static void mai
for(int x=0;xYour for loopfor(int x=0;x)谢谢这是答案!不知怎的,我忘了数组[3]在打印或存储时只升到数组[2]……谢谢!谢谢这是答案!不知怎的,我忘了数组[3]在打印或存储时只升到数组[2]……谢谢!
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)