I have a text file that reads:
1 2 3 4 5
6 7 8 9 1
8 3 9 7 1
9 3 4 8 2
8 7 1 6 5
where each number is separated by a tab.
My question is, is there a simple way to sum the columns of numbers using java? I want it to sum 1+6+8+9+8, 2+7+3+3+7, etc. I am reading the file using:
public static boolean testMagic(String pathName) throws IOException {
// Open the file
BufferedReader reader = new BufferedReader(new FileReader(pathName));
// For each line in the file ...
String line;
while ((line = reader.readLine()) != null) {
// ... sum each column of numbers
}
reader.close();
return isMagic;
}
public static void main(String[] args) throws IOException {
String[] fileNames = { "MyFile.txt" };
}
is the number of columns known or variable? You can just create an array of sums and parse each line into ints and the add it to the correct sum.
If you don’t know the number of columns beforehand use an
ArrayListand do the first line differently so that you can figure out the number of columns.