带有readfile的ArrayIndexOutOfBounds创建Java对象数组

时间:2013-03-12 13:04:56

标签: java arrays object readfile

我一直在练习open uni的练习,这需要我从文本文件中检索的信息中创建几个对象..它几乎可以正常工作,但我一直在第58行得到一个ArrayIndexOutOfBoundsException:1。可能是一个简单的问题但是我我是一个新手,它让我难倒我确信我在我的代币[]编号为0 - 8,因此我不确定会出现什么问题......任何帮助都会很棒

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;
}

2 个答案:

答案 0 :(得分:0)

命令oldInfo.split("\\s");未按预期返回长度为5或更长的数组。

答案 1 :(得分:0)

您的String tokens[] = oldInfo.split("\\s");对于您正在使用的索引来说还不够大......或者索引对于它来说太大了。我建议你做一些调试或只是显示一些信息而不是只是想找到bug。代码显然没有按照您的预期执行。

你也不应该重用那个z变量,在for循环中声明它: for (int z = 0; ...