Federico Federico - 3 months ago 4
Java Question

Recursive calculation in Java

I'm trying to solve a calculation problem in Java.

Suppose my data looks as follows:


It's a list of ordered pairs, in the form of [int],[double]. Each line in my file contains one pair. The file can contain seven to seven thousand of those lines, all of them formatted as plain text.

Each [int] must be subtracted from the [int] one line above and the result written onto another file. The same calculation must be done for every [double]. For example, in the data reported above, the calculation should be:

478-476 -> result to file
476-474 -> result to file
2.098-2.0939 -> result to file
2.0939-2.09 -> result to file

and so on.

I beg your pardon if this question will look trivial for the vast majority of you, but after weeks trying to solve it, I got nowhere. I also had troubles finding something even remotely similar on this board!
Any help will be appreciated.


  1. Read the file
  2. Build the result
  3. Write to a file

For the 1. task there are already several good answers here, for example try this one: Reading a plain text file in Java.

You see, we are able to read a file line per line. You may build a List<String> by that which contains the lines of your file.

To the 2. task. Let's iterate through all lines and build the result, again a List<String>.

List<String> inputLines = ...

List<String> outputLines = new LinkedList<String>();
int lastInt = 0;
int lastDouble = 0;
boolean firstValue = true;
for (String line : inputLines) {
    // Split by ",", then values[0] is the integer and values[1] the double
    String[] values = line.split(",");
    int currentInt = Integer.parseInt(values[0]);
    double currentDouble = Double.parseDouble(values[1]);

    if (firstValue) {
        // Nothing to compare to on the first run
        firstValue = false;
    } else {
        // Compare to last values and build the result
        int diffInt = lastInt - currentInt;
        double diffDouble = lastDouble - currentDouble;

        String outputLine = diffInt + "," + diffDouble;

    // Current values get last values
    lastInt = currentInt;
    lastDouble = currentDouble;

For the 3. task there are again good solutions on SO. You need to iterate through outputLines and save each line in a file: How to create a file and write to a file in Java?