我正在从文本文件中读取,并将我的对象(Dogs)的参数设置为文本文件中的信息。这是一个非常简单的任务,但每次我尝试访问字段[1]或字段[2]时,我都会一直得到一个数组越界错误。我的代码如下:
BufferedReader inFile = new BufferedReader(new FileReader("dogslist.txt"));
String line = inFile.readLine();
int count = 0;
Dogs[] parlour = new Dogs[16];
while(line != null)
{
String[] field = line.split("#");
int age = Integer.parseInt(field[2]);
parlour[count] = new Dogs(field[0],field[1],age);
System.out.println(parlour[count]);
count++;
line = inFile.readLine();
}
以下是文本文件的内容:
Jerry#German Sheapord#4
Owen#cat#3
Morgan#MathsGenius#7
错误,文本文件和代码的文本文件:http://pastebin.com/SznqE45i
答案 0 :(得分:4)
您可以通过在代码中更“防守”并验证每个输入行是否包含内容以及拆分后的数组符合预期来解决您的问题:
BufferedReader inFile = new BufferedReader(new FileReader("dogslist.txt"));
String line;
int count = 0;
Dogs[] parlour = new Dogs[16];
while((line = inFile.readLine()) != null)
{
if(line.trim().length() > 0){
String[] field = line.split("#");
if(field.length < 3){
System.out.println("Invalid line encountered: " + line);
}
else{
int age = Integer.parseInt(field[2]);
parlour[count] = new Dogs(field[0],field[1],age);
System.out.println(parlour[count]);
count++;
}
}
}