'Can't get my integer to increase constantly in method
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 1:[1]
You should read up about the scope and lifespan of variables in Java. You declare a local variable inside the function, which is "created" and initiated (to 0) when you write:
int numb = 0;
This variable is only visible inside this current function call. After your function is executed the variable and its value is invalidated and destroyed. When calling the function again, the variable is created and initiated (to 0) again.
If your variable needs to "survive" multiple calls of your function consider to declare it outside of the function:
private static int numb = 0;
public static void recursionTest() {
System.out.println(numb);
while (numb != -1) {
numb =+ 1;
}
recursionTest();
}
Or pass it as a parameter:
public static void main(String[] args) {
recursionTest(0);
}
public static void recursionTest(int numb) {
System.out.println(numb);
while (numb != -1) {
numb =+ 1;
}
recursionTest(numb);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Misc08 |
