rickyhitman10
rickyhitman10

Reputation: 59

summing column by column in java

i have file txt in desktop :
1   5     23
2   5     25  
3   30    36

i want sum column by column 1 + 2 + 3 =... and 5 + 5...n and 23,...n

Scanner sc = new Scanner (file("patch");
while (sc.hasNextLine)

{

//each sum by column

}

help me please thanks

Upvotes: 1

Views: 2705

Answers (3)

Elliott Frisch
Elliott Frisch

Reputation: 201447

I would use a try-with-resources to clean up my Scanner using the File. Also, you could construct a Scanner around the line of input to get your int columns (that doesn't need to be closed because String(s) aren't closable anyway). Something like,

try (Scanner sc = new Scanner(new File("patch"))) {
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        Scanner row = new Scanner(line);
        long sum = 0;
        int count = 0;
        while (row.hasNextInt()) {
            int val = row.nextInt();
            if (count == 0) {
                System.out.print(val);
            } else {
                System.out.printf(" + %d", val);
            }
            sum += val;
            count++;
        }
        System.out.println(" = " + sum);
    }
} catch (IOException e) {
    e.printStackTrace();
}

As the Scanner(String) Constructor Javadoc documents

Constructs a new Scanner that produces values scanned from the specified string.

Edit To sum the columns is a little trickier, but you could read everything into a multidimensional List<List<Integer>> like

try (Scanner sc = new Scanner(new File("patch"))) {
    List<List<Integer>> rows = new ArrayList<>();
    int colCount = 0;
    while (sc.hasNextLine()) {
        List<Integer> al = new ArrayList<>();
        String line = sc.nextLine();
        Scanner row = new Scanner(line);
        colCount = 0;
        while (row.hasNextInt()) {
            colCount++;
            int val = row.nextInt();
            al.add(val);
        }
        rows.add(al);
    }
    for (int i = 0; i < colCount; i++) {
        long sum = 0;
        for (List<Integer> row : rows) {
            sum += row.get(i);
        }
        if (i != 0) {
            System.out.print("\t");
        }
        System.out.print(sum);
    }
    System.out.println();
} catch (IOException e) {
    e.printStackTrace();
}

Edit 2 For efficiencies sake, you might prefer to use a Map like

try (Scanner sc = new Scanner(new File("patch"))) {
    Map<Integer, Integer> cols = new HashMap<>();
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        Scanner row = new Scanner(line);
        int colCount = 0;
        while (row.hasNextInt()) {
            int val = row.nextInt();
            if (cols.containsKey(colCount)) {
                val += cols.get(colCount);
            }
            cols.put(colCount, val);
            colCount++;
        }
    }
    for (int i : cols.values()) {
        System.out.printf("%d\t", i);
    }
    System.out.println();
} catch (IOException e) {
    e.printStackTrace();
}

Upvotes: 3

Sangeeth
Sangeeth

Reputation: 634

Please find the code. Please go through the comments. This is one way of doing for your reference. I want you to try other ways to improve your knowledge rather just using this code.

int sums[] = null;
    while (sc.hasNextLine())
    {
        String row = sc.next();// get first row
        String[] values = row.split(" ");// split by space
        if(null == sums)
        {
            sums = new int[values.length];// create sum array with first row size
        }
        int index = 0;
        for (String value : values)
        {
            sums[index] = sums[index]+Integer.parseInt(value);//adding current row value to current sum
            index++;
        }
    }
    if(null != sums)
    {
        int index=0;
        for (int sum : sums)
        {
            System.out.println("Sum of column "+index+" : "+sum);// Printing each column sum
            index++;
        }
    }

Upvotes: 1

dvrnaidu
dvrnaidu

Reputation: 151

If your file is CSV formatted, then split line by comma(",") and find number of columns based on split array length.

Like below:

String line = sc.next();
String[] lineArr = line.split(",");
int len = lineArr.length;

create array of arraylists of size len and store each column field in the respective arraylist. finally, at the end apply sum on each arraylist to calculate sum of each column values.

Upvotes: 0

Related Questions