【发布时间】: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