當我調用這個函數時,我得到了一個ArrayIndexOutOfBoundsException
,但並不總是如此。出10次嘗試,我得到了一個錯誤3次,其餘7次它工作得很好。Java中的BufferedReader偶然出錯
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線恰好是如果有條件本身。
即使更改後,錯誤仍然存在。
哪條線是第215? – BackSlash
嘗試改變'if(coords [0]!= null && coords [1]!= null){'to'if(coords.length == 2){' – johnchen902
您可以檢查if條件的大小的數組coords.size> = 2 &&做你的驗證 – Siva