Issue
I am fairly new to java (and most programming languages as a whole) and am trying to get some unfamiliar concepts down, one of which is recursion. To test it out I tried making it so that a number would constantly increase and get displayed.
public static void recursionTest() {
int numb = 0;
System.out.println(numb);
numb += 1;
recursionTest();
}
I tried writing it out like this, but it will only print the number 0 constantly with no increase. I then tried putting before println, but it only produced the number 1. I then tried replacing with a while loop.
public static void recursionTest() {
int numb = 0;
System.out.println(numb);
while (numb != -1) {
numb =+ 1;
}
recursionTest();
}
This ended up printing out just a single 0, I then tried moving it above println like I did before, but it then didn't display anything. Is there something I'm missing? Sorry if my question is stupid.
Solution
As you have defined it, numb
is a local variable scoped within the method. It's created with the instruction int numb = 0
at the beginning of each call of the method, and destroyed at the end of it. Each time you call the method (even if the call is recursive) is a different variable. With the same name in the code, but it's a different one.
In order to achieve a counter you should either define numb
as a static field of the class or pass as parameter to the method. You can do something like the following:
Option 1 (static field):
public class TheClass {
static int numb = 0;
public static void recursionTest() {
System.out.println(numb);
numb += 1;
recursionTest();
}
}
Option 2 (pass as parameter):
public class TheClass {
public static void recursionTest(int numb) {
System.out.println(numb);
numb += 1;
recursionTest(numb);
}
}
In the second attempt you are doing the System.out.println
outside the while
loop, so you are printing the value only once. Moreover, the recursive call is never being done due to the infinite while loop, but in the case you put a limit to the loop, the new call to the same method will result in the counter being reset because the same reason as before.
Answered By - Alfredo Tostón
Answer Checked By - Katrina (JavaFixing Volunteer)