二维数组不起作用

时间:2018-05-03 15:38:45

标签: java arrays object for-loop arraylist

我有一个二维数组从文本文件中获取特定的动物,但由于某种原因它根本不起作用。我已检查过任何错误,但我没有错误,只是没有输出。它只是输出“找不到文件”,我知道这不是真的

TEXT

Hat, dog, cat, mouse
Cow, animal, small, big, heavy
Right, left, up, down ,behind
Bike, soccer, football, tennis, table-tennis

CODE

try {
    animals = new Scanner(new File("animals.txt"));
    // code for number of lines start
    File file =new File("animals.txt");

    if(file.exists()){

        FileReader fr = new FileReader(file);
        LineNumberReader lnr = new LineNumberReader(fr);

        int linenumber = 0;

        while (lnr.readLine() != null){
            linenumber++;
        }

        lnr.close();

        // code for number of lines end

        String[][] animal = new String [linenumber][];

        for (int i = 0; i < linenumber; i++) {
            String line = animals.nextLine();
            String [] oneRowAnimals = line.split(",");
            for(int j=0; j<oneRowAnimals.length; j++) {

                // Here you are storing animals
                animal[i][j] = oneRowAnimals[j];
            }
        }
        // Now you can access them by index.

        System.out.println(animal[2][2]);

    } else{
        System.out.println("File does not exists!");
    }
} catch(Exception e) {
    System.out.println("could not find file");
}

1 个答案:

答案 0 :(得分:1)

您需要使用大小初始化子数组。尝试通过索引访问这些未初始化的子数组会导致NullPointerException。插入代码:

animal[i] = new String[oneRowAnimals.length];

行后:

String [] oneRowAnimals = line.split(",");

正如评论中所建议的那样,在调试此类代码时非常有用,以避免吞噬所有类型的异常。捕获try块中的代码可能抛出的特定异常,或者至少在catch块中打印更多信息,这将是一个好主意。