当我调用此函数时,我会得到一个ArrayIndexOutOfBoundsException
,但并非总是如此。在10次尝试中,我3次出现错误,其余7次工作得很好。
void readTrainingData(Model m) throws FileNotFoundException {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("training_data.csv"));
} catch (IOException ex) {
throw new FileNotFoundException();
}
String line = "";
int i = 0;
int j;
try {
while((line = br.readLine()) != null) {
String[] coords = line.split(",");
if (coords[0] != null && coords[1] != null) {
m.x[i] = Float.parseFloat(coords[0]);
m.y[i] = Float.parseFloat(coords[1]);
}
else {
System.out.println("Check training_data.csv");
}
j = 0;
i++;
}
} catch (IOException ex) {
System.out.println("Problem reading file");
throw new RuntimeException(ex);
}
}
错误如下:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at polygonprobability.Util.readTrainingData(Util.java:215)
我无法调试它,因为每当我尝试调试时,我都不会收到错误。
我彻底糊涂了。请帮忙。
编辑:我将条件更改为
if (coords[0] != null && coords[1] != null && coords.length == 2) {
m.x[i] = Float.parseFloat(coords[0]);
m.y[i] = Float.parseFloat(coords[1]);
}
第 215 行恰好是 if 条件本身。
即使更改后,错误仍然存在。
最佳答案
进行此更改
if (coords.length == 2 && coords[0] != null && coords[1] != null ) {
m.x[i] = Float.parseFloat(coords[0]);
m.y[i] = Float.parseFloat(coords[1]);
}
关于java - Java 中 BufferedReader 偶尔出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17923156/