gpt4 book ai didi

java - 字符串分割导致数组越界

转载 作者:行者123 更新时间:2023-12-01 18:05:29 25 4
gpt4 key购买 nike

我正在读取文本文件,并将对象(狗)的参数设置为文本文件上的信息。这是一个非常简单的任务,但每次尝试访问 field[1] 或 field[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

最佳答案

您可以通过在代码中更加“防御”并验证每个输入行是否有内容以及拆分后的数组是否符合预期来解决您的问题:

    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++;
}
}
}

关于java - 字符串分割导致数组越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36793542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com