0

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

kuk
  • 127
  • 1
  • 8
  • 1
    What have you tried so far? do you already read lines from a file? – f1sh Oct 07 '20 at 21:39
  • Please show us what you have tried so far. For reading from a file I suggest searching online for "java read lines from file", and for separating numbers on lines I suggest searching for "java find character in string" and "java substring tutorial". – sorifiend Oct 07 '20 at 21:42
  • Maybe look at "Java convert String to int" and "Java split String" in google – Big_Bad_E Oct 07 '20 at 22:01

1 Answers1

0

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);
        
   }  
}
Moe
  • 462
  • 2
  • 16
  • Thank you for your answer! Just curious, what would need to be changed so that the code could also read an undefined number of columns? – kuk Oct 09 '20 at 21:40