Я пытаюсь суммировать значения из текстового файла с помощью рекурсивного метода, значения в текстовом файле разделяются точкой с запятой. Данные в текстовом файле хранится так:значения суммы с помощью рекурсивного метода
7708190034; Environment; 10500; Schools; 8000; Health care; 9500
9609131234; Environment; 20000; Schools; 20000; Health care; 18000
Скажем, я хочу суммировать значения для окружающей среды, так что в этом случае результат будет что-то вроде «Сумма для окружающей среды: 30500» и т.д. Другими словами, , для среды Я хочу прочитать часть для среды в первой строке (значение 10500), а затем прочитать следующую строку и добавить найденное значение (в данном случае 20000) к первому, и, наконец, распечатать сумму для него. И суммирование должно проводиться с помощью рекурсивного метода. На данный момент я использую следующий код:
/*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;
}
На данный момент я только получить выход так:
Sum for environment: 0
Sum for environment: 0
Sum for environment: 0
Но DESIRED результат должен быть таким:
Sum for environment: 30500
Что мне не хватает или что-то не так?
Подсказка: где вы добавляете что-то в список? –
Внутри оператора if в методе readEnvironment я добавляю значения в массив «environmentum» с линией environmentum.add (number); – eqinna