从CSV文件读取的每列的行的值的总和

时间:2016-10-16 07:56:29

标签: java multidimensional-array

我正在尝试从包含10行和4列的CSV文件中读取并在读取数据后,我想添加每列的所有行。对于每列的每一行都有一个值。假设,如果column1的row1为0,则它​​的值为3,并且每列的每一行都相同。例如,如果列的10行是 - 1 2 3 4 五 0 1 0 0 0 那么总和应该是16.这是迄今为止的代码 -

public static void main(String[] args) throws Exception
    {
        String line=null;
        try{
            BufferedReader br=new BufferedReader(new FileReader(filepath));


                while((line=br.readLine())!=null){

                    String[] distance=line.split(",");
                    System.out.println(line);    
                }
                br.close();

        }catch(IOException e){
            e.printStackTrace();
        }
    }

现在,我想找到每列所有这些值的总和。帮助解决这个问题将不胜感激。感谢

2 个答案:

答案 0 :(得分:1)

免责声明:您必须使用CsvReader(请参阅here),以下内容仅用于演示解决方案。

以单遍计算列总和:

public class CsvReader {
    private static final int NUMBER_OF_COLUMNS = 4;

    public static void main(String[] args) throws IOException {

        Scanner lineScanner = new Scanner(Paths.get("path.to.your.csv.file"));

        int[] sumPerColumn = new int[NUMBER_OF_COLUMNS];

        while (lineScanner.hasNextLine()) {
            String line = lineScanner.nextLine();
            String[] values = line.split(",");

            for (int col = 0; col < values.length; col++) {
                sumPerColumn[col] += Integer.parseInt(values[col]);
            }
        }

        System.out.println(Arrays.toString(sumPerColumn));
    }
}

答案 1 :(得分:0)

使用ArrayList存储已读取的行,然后编写一个实用程序方法,该方法将此数据中的所需行相加。像这样:

    public static void main(String[] args) throws Exception
    {
        String line=null;

        // here we create a container for readed and splitted lines
        ArrayList<String[]> lines = new ArrayList<String[]>();
        try{
            BufferedReader br=new BufferedReader(new FileReader(filepath));


                while((line=br.readLine())!=null){

                    String[] distance=line.split(",");

                    // here we add each readed and splitted line
                    lines.add(distance);
                    System.out.println(line);    
                }
                br.close();

        }catch(IOException e){
            e.printStackTrace();
        }


        // here we sum for a particular column.
        int columnToSum = 4;
        int sum = sumRows(lines, columnToSum );
        System.out.println("The sum of column "+ columnToSum +" is: " + sum); 
    }


    public static int sumRows(ArrayList<String[]> lines, int columnToSum)         
    {
        int sum = 0;
        for (String[] line: lines) {
            sum = sum + Integer.parseInt(line[columnToSum]);
        }
        return sum;
    }