Java servlet,从文件读取,数组出界



我正在制作一个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

怎么了?以及如何解决它?

例如,

如果文件中有一个空行,或者格式不同的行,或者空格实际上是制表符(也许还有更多原因),则此代码将失败。如果你想进行防御性编程,你应该做:

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...
    }
}

我按如下方式运行您的代码,这很好。 确保您的数据文件是 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());
        }
    }
}

列数组中没有索引 4。检查列数组的长度。它将小于 5,当访问数组的非法索引时,会抛出 ArrayIndexOutOfBoundException。像这样检查数组长度

  if( columns != null && columns.length >= 5 )
        sum = sum + Integer.parseInt(columns[4]);

最新更新