我一直在练习 open uni 的练习,它要求我从从文本文件中检索到的信息创建几个对象..它几乎可以工作,但我在第 58 行不断收到 ArrayIndexOutOfBoundsException : 1 。可能是一个简单的问题,但因为我是新手对此,我感到很困惑
package ReadWriteObjectThang;
import java.util.Scanner;
public class NinjaListMain {
public static void main(String[] args) {
FileReadWrite jin = new FileReadWrite();
Scanner scanny = new Scanner(System.in);
Ninja ninja[] = new Ninja[3];
System.out.println("Enter 1 to create 3 new Ninja Objects \n Enter 2 to create 3 Ninja Objects from file");
int choice = scanny.nextInt();
scanny.nextLine();
int hp = 0;
int x = 1;
int z = 0;
String info = " ";
if(choice==1){
System.out.println("Enter a name for your ninja crew");
String newCrew = scanny.nextLine();
for(z = 0;z<3;z++){
System.out.println("Enter a name: ");
String name = scanny.nextLine();
System.out.println("Enter a weapon: ");
String weapon = scanny.nextLine();
System.out.println("Enter hitpoints in whole numbers: ");
hp = scanny.nextInt();
scanny.nextLine();
ninja[z] = new Ninja(name,weapon,hp);
info = info + name + " " + weapon + " " + hp + ",";
}
jin.write(newCrew, info);
}
else if(choice==2){
System.out.println("Enter file name for ninjas to create");
String oldCrew = scanny.nextLine();
String oldInfo = jin.read(oldCrew);
String tokens[] = oldInfo.split("\\s");
int w = 0;
for(z = 0;z < 3;z++){
if(z==0)
w = 0;
else if(z==1)
w = 3;
else
w = 6;
String name = tokens[0 + w];
String weapon = tokens[1 + w]; //AIOOBE happens here or line below
hp = Integer.parseInt(tokens[2 + w]);
ninja[z] = new Ninja(name,weapon,hp);
}
}
for(int g = 0;g<3;g++){
System.out.println(ninja[g].getName() + " " + ninja[g].getWeapon() + " " + ninja[g].getHP());
}
}
}
public class Ninja {
private String name;
private String weapon;
private int hitpoints;
public Ninja(String a, String b, int c){
name = a;
weapon = b;
hitpoints = c;
}