我正在创建一个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页面时,我得到了
java.lang.ArrayIndexOutOfBoundsException: 4
怎么了?以及如何解决它?
答案 0 :(得分:3)
如果有例如此代码将失败文件中的空行,或者格式不同的行,或者空格实际是制表符(可能有更多原因)。如果你想要进行防御性编程,你应该这样做:
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...
}
}
答案 1 :(得分:0)
您的columns数组中没有索引4。检查列数组的长度。它将小于5,当访问数组的非法索引时抛出ArrayIndexOutOfBoundException。像这样检查数组长度
if( columns != null && columns.length >= 5 )
sum = sum + Integer.parseInt(columns[4]);
答案 2 :(得分:0)
我按照以下方式运行您的代码,很好。确保您的数据文件是ASCII
import java.io.*;
public class Test{
public static void main(String[] args){
try{
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("Sun:" + sum);
}catch(Exception e){
System.out.println("error:" + e.getMessage());
}
}
}