+ 1
why addoneto method cannot find variable x which is in the same class?
5 Answers
+ 6
Just put static keyword outside of a main method it will make variable x a kind of global variable it can be access from anywhere
public class MyClass {
//private static int x;
public static void main(String[ ] args) {
int x = 5;
addOneTo(x);
System.out.println(x);
}
static void addOneTo(int num) {
num = num + 1;
x = num;
}
}
+ 1
Maybe you want to do some thing like this?
https://code.sololearn.com/c2dsZlJgpt3i/?ref=app
+ 1
Thomas i have tried this before .thanks
+ 1
Or this way, simpler
https://code.sololearn.com/cGg2c8Qt3HIF/?ref=app
+ 1
Thomas good