0

我一直在练习 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;
}
4

2 回答 2

0

该命令oldInfo.split("\\s");没有像您期望的那样返回长度为 5 或更长的数组。

于 2013-03-12T13:10:07.500 回答
0

对于您String tokens[] = oldInfo.split("\\s");正在使用的索引,您的索引不够大...或者索引对于它来说太大了。我建议您进行一些调试或简单地显示一些信息,而不是仅仅考虑查找错误。该代码显然没有按照您的预期执行。

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

于 2013-03-12T13:11:38.013 回答