I have been practising an exercise for open uni which requires me to create several objects from information retrieved from a text file ..it's almost working but I keep getting an ArrayIndexOutOfBoundsException : 1 at line 58. Probably a simple issue but as I am a newbie at this it has me stumped I am sure that I am in bounds with my tokens[] numbering 0 - 8 so I am not sure what is going wrong...any help would be awesome
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;
}
1+w
andtokens.length()
, as1+w may be > tokens.length()
– Abubakkar Rangara Mar 12 at 13:08