Reputation: 57
Okay here is my situation:
I have a recursive function which is calculating and printing something to screen. Now I need that output to be to a file.
So I did this:
public void recursiveFn(int value) throws FileNotFoundException {
recursiveFn(a);
PrintWriter fileOP = new PrintWriter("file.txt")
fileOp.printf(somevaluefromthisfunction)
}
Problem with this approach is, every time a call is made to that function recursively, a new file is being created and all the previous recursive calls data is being deleted.
Now my approach was to make the file create deflation outside this function. This is what I did:
public class MyClass {
PrintWriter fileOP = new PrintWriter("file.txt") //line 2
public void recursiveFn(int value) {
recursiveFn(a);
fileOp.printf(somevaluefromthisfunction)
}
}
the issue with this? I'm getting this error: "Unhandled exception type FileNotFoundException" at line 2. I lost almost 5% of my hair in the process of debugging this error!
Upvotes: 0
Views: 2945
Reputation: 81
The problem is that your variable initialization can throw an exception that you must handle. Others have shown a few different ways to handle this. The best, IMO, is to have a method that sets up everything the recursive method needs (like the PrintWriter) and then calls the recursive method.
public class MyClass {
public void doSomething(int value) {
PrintWriter fileOP = new PrintWriter("file.txt");
this.recursiveFn(value,fileOP);
}
public void recursiveFn(int value,PrintWriter fileOp) {
int a = value + 1; // Or whatever
recursiveFn(a,fileOp);
fileOp.printf(somevaluefromthisfunction);
}
}
Upvotes: 2
Reputation: 41281
Set the fileOP in the constructor:
public class MyClass {
PrintWriter fileOP; //line 2
public void recursiveFn(int value) {
recursiveFn(a);
fileOp.printf(somevaluefromthisfunction)
}
public MyClass(){
try{
fileOP = new PrintWriter("file.txt");
} catch (FileNotFoundException e){
// do whatever you need to do to handle it
}
}
}
You can also pass the printwriter in the recursive definition:
public void recursiveFn(PrintWriter fOP, int a) throws FileNotFoundException {
recursiveFn(fOP, a);
fOP.printf(someFunc(a));
}
I'm guessing you'll want to tweak the recursion of the function a bit to be logical and not be infinite.
Upvotes: 0