+ 1

why addoneto method cannot find variable x which is in the same class?

https://code.sololearn.com/cimawFlX2q6B/?ref=app

26th Dec 2019, 3:35 PM
jcx2010
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; } }
28th Dec 2019, 5:12 AM
0_O-[MĂ€gĂĄr_SĂĄm_ÄkĂ _NĂŒllpÞïntĂȘr_ÈxĂ«cĂ©ptïön]~~
0_O-[MĂ€gĂĄr_SĂĄm_ÄkĂ _NĂŒllpÞïntĂȘr_ÈxĂ«cĂ©ptïön]~~ - avatar
+ 1
Maybe you want to do some thing like this? https://code.sololearn.com/c2dsZlJgpt3i/?ref=app
26th Dec 2019, 3:52 PM
Coding Cat
Coding Cat - avatar
+ 1
Thomas i have tried this before .thanks
26th Dec 2019, 3:54 PM
jcx2010
26th Dec 2019, 3:55 PM
Coding Cat
Coding Cat - avatar
+ 1
Thomas good
26th Dec 2019, 3:58 PM
jcx2010