我正在制作一个java servlet,我的任务是获取文件中写入的产品的总成本:
category1 1 10 101 1 good1
category6 2 11 105 2 good5
category1 5 13 103 3 good4
category3 6 14 102 4 good2
category5 3 12 107 2 good1
费用在第 4 栏。我已经写了:
public int Sum_of_Elements()throws IOException{
int sum = 0;
BufferedReader br = new BufferedReader(new FileReader("/Data.txt"));
String line = "";
while((line=br.readLine())!=null){
String[] columns = line.split(" ");
sum = sum + Integer.parseInt(columns[4]);
}
System.out.println(sum);
return sum;
}
而且它不起作用。当我进入 servlet 页面时,我得到 p>
java.lang.ArrayIndexOutOfBoundsException: 4
怎么了?以及如何修复它?
最佳答案
如果存在以下情况,此代码将失败:文件中的空行,或者格式不同的行,或者空格实际上是制表符(也许还有更多原因)。如果你想进行防御性编程,你应该这样做:
while((line=br.readLine())!=null) {
String[] columns = line.split(" ");
if( columns != null && columns.length >= 5 ) {
sum = sum + Integer.parseInt(columns[4]);
}
else {
// do what you must here; it may be an error to encounter such a line:
throw new IllegalArgumentException("malformatted line: " + line);
// or it may be OK to swallow the exceptional case
// or you may only need to silently log it:
logger.warn("malformatted line: " + line);
// etc...
}
}
关于Java servlet,从文件读取,数组越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20815501/