首页 > 解决方案 > 二维数组不起作用

问题描述

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

文本

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

代码

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

标签: javaarraysobjectfor-looparraylist

解决方案


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

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

行后:

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

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


推荐阅读