I'm trying to sum values from a text file with a recursive method, the values in the textfile are separated by a semicolon. The data in the textfile is stored like this:
7708190034; Environment; 10500; Schools; 8000; Health care; 9500
9609131234; Environment; 20000; Schools; 20000; Health care; 18000
Let's say I want to sum the values for environment so that in this case the output would be something like "Sum for environment: 30500" etc. In other words, for environment I want to read the part for environment in the first line (value 10500) and then read the next line and add the found value (in this case 20000) to the first one, and finally print out the sum for it. And the summation should be done with a recursive method. At the moment I use the following code:
/*Main method:*/
public static void main(String[] args) throws IOException {
//Invoke method to sum environments through recursive method:
readEnvironment();
}
/*Method to read environment values:*/
static void readEnvironment() throws IOException {
List<Integer> environmentsum = new ArrayList<>();
File file = new File("sums.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
// Read the first line from the file
String s = br.readLine();
// As long as we have not reached the end of the file...
while (s != null) {
// Split the string read from the file by the separator ;
String[] data = s.split(";");
//As long as the string has 6 parts...
if (data.length == 6) {
// We know that the second part in the line is the value for an environment:
int number = Integer.parseInt(data[2]);
//Add the found number to the array:
environmentsum.add(number);
}
int sum = 0;
//Invoke recursive method:
sum = sum(environmentsum, 0);
System.out.println("Sum for environment: " + sum);
//Read next line:
s = br.readLine();
}
br.close();
}
/*Recursive method to sum the values:*/
static int sum(List<Integer> t, int index) {
//If there are no elements in the array:
if (index == t.size()) {
return 0;
}
int sum = t.get(index) + sum(t, index + 1);
return sum;
}
At the moment I only get an output like this:
Sum for environment: 0
Sum for environment: 0
Sum for environment: 0
But the DESIRED result should be like this:
Sum for environment: 30500
What am I missing or doing wrong?