Search code examples
javajava.util.scannerbufferedreaderfilereader

How to sum numbers that are in columns from a text file in Java?


I am trying to read from a file with multiple lines and then add the numbers in columns. However, I struggle to separate numbers into int variables from same lines so that I could add them eventually.

Basically, I would like to know how to read from a file and sum the columns below:

11 33
22 2
33 1

So that I would get 66 and 36


Solution

  • Assuming the file name is "filename.txt"...

    import java.io.BufferedReader;
    import java.io.FileReader;
    
    public class SumColumns  
    {  
       public static void main(String args[])
       {  
            int firstCol = 0, secondCol = 0;
            BufferedReader reader;
            try {
    
                reader = new BufferedReader(new FileReader("./filename.txt"));
                
                String line;
                String[] columns;
                
                while ((line = reader.readLine()) != null) {
                    columns = line.split(" ");
                    firstCol += Integer.parseInt(columns[0]);
                    secondCol += Integer.parseInt(columns[1]);
                }
                
            } catch (Exception e) {
    
            }
            
    
            System.out.println(firstCol);
            System.out.println(secondCol);
            
       }  
    }