0

So I have this recursive method:

public static void returnValues(int i) throws IOException {
    double division = (Math.sqrt(inputs.get(i)));
    if (i == 0) {
        System.out.println(inputs.get(i));
        System.out.println("Success! Check your desktop to see the results");
    }   
    else if (division == (int)division) {
        System.out.println(inputs.get(i));
        i--;
        returnValues(i);
    }
    else {
        i--;
        returnValues(i);
    }         
}

Every time you see a System.out.println(), I need the program to write the value of inputs.get(i) in a new line of a .txt file. The problem is, every time I try to do so, Java will automatically overwrite the file every time the method calls itself again, so at the end of the execution, the only thing that is written on the file is the output of the last iteration.

Any ideas on how to accomplish this?

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Depends on how you write into the txt file which you haven't shown us. – Thiyagu Sep 06 '20 at 05:44
  • 1
    Does this answer your question? [How to append text to an existing file in Java?](https://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java) – J. García Sep 06 '20 at 05:45
  • Would you please paste the entire code here? As far as I can tell, it will do what you want. Are you directing this to a file externally to your program? Perhaps by ``java someName > xxx.txt`` ? – NomadMaker Sep 06 '20 at 06:06
  • If using java 11+ , based on aforementioned answer and the reference for the `Files` class. Seems you can do something as simple as: `Files.writeString(Paths.get("the_file.txt"), String.valueOf(inputs.get(i)) + System.getProperty("line.separator"), StandardOpenOption.CREATE, StandardOpenOption.APPEND);` either enclosed in a try-catch or setting your function to throw `IOException`. That said your code seems to be only be trying to append those lines if the result of `Math.sqrt()` is an interger or your last iteration/recursion, not sure if that's what you are trying to accomplish. – J. García Sep 06 '20 at 06:07
  • In fact, the code that you have shown us is almost completely irrelevant to the Question that you asked. For a start, it doesn't even try to write to a file. If you showed us the code where you tried to do that, we could point out what you did wrong. But the dup link tells you the right way to do it. – Stephen C Sep 06 '20 at 06:21

0 Answers0