【发布时间】:2013-04-13 02:16:59
【问题描述】:
我可以使用扫描仪读取文件。当返回类型为 void 时,我可以读取数据并将其打印到控制台,但是,随后它会立即引发 ArrayOutOfBoundsException。理想情况下,我想作为字符串数组返回,但是,我只得到一个 ArrayOutOfBoundsException。在这两种情况下,异常都会在 Cancers[j] = input.nextLine() 处引发。我已经确保数组的大小是正确的。当我不对它的大小进行硬编码时,编译器会在同一行抛出 NullPointerException(这是有道理的,因为未声明数组的大小)。
我需要该方法返回一个字符串数组,因为我必须对其进行额外的操作。
public String[] readCancer() {
cancers = new String[21];
int j = 0;
try {
input = new Scanner(myData);
String result;
while(input.hasNext()) {
++j;
cancers[j] = input.nextLine();
//System.out.println(cancers[j]);
}
} catch (FileNotFoundException fnfx) {
JOptionPane.showMessageDialog(null, "Txt file could not be found");
}
return cancers;
}
我尝试以稍微不同的方式重写该方法,但我得到了同样的错误,只是这次是在 output[i] = result;
public String[] readCancers() {
FileInputStream fis;
DataInputStream dis;
BufferedReader br;
InputStreamReader isr;
String result;
String[] output = new String[21];
int i = 0;
try {
fis = new FileInputStream(myData);
dis = new DataInputStream(fis);
isr = new InputStreamReader(dis);
br = new BufferedReader(isr);
while((result = br.readLine()) != null) {
++i;
output[i] = result;
}
} catch (FileNotFoundException fnfx) {
fnfx.printStackTrace();
} catch (IOException iox) {
iox.printStackTrace();
}
return output;
}
【问题讨论】:
-
在对它们进行任何操作之前,您正在递增 j 和 i。因此,您的数组从 1 而不是 0 开始,只给您 20 而不是 21 个数组元素。我假设您的文件有 21 项,所以当添加第 21 项时,它会超出范围。
-
做一些类似癌症的事情[j++];会给你在cancers[j]处添加一个元素然后在下一次增加j的效果。 PS我希望你在做医疗工作,否则癌症是一个可怕的变量名。
-
哥们,你能把你的文本文件贴出来让我们知道文本文件有多少行吗?
-
@nickecarlo 您的建议非常有效!文本文件包含各种癌症类型的信息,否则我同意这将是一个可怕的名称。
-
@RaviTrivedi 我的文本文件从第 1 行到第 22 行。