【问题标题】:2-dimensional array not working二维数组不起作用
【发布时间】:2018-10-13 23:59:30
【问题描述】:

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

文字

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

【问题讨论】:

  • animal.txt 必须在类路径中。
  • 我建议删除 try catch 并查看它抛出了什么异常。或者至少将异常更改为找不到文件时引发的特定错误。在这种情况下,它目前正在毫无区别地捕获所有异常。

标签: java arrays object for-loop arraylist


【解决方案1】:

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

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

行后:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-30
    • 2021-11-18
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多