+ 2
What is the mistake in the code.
I want to print the value of a by the max method but It is not working So I want to know why and how can I fix it. https://code.sololearn.com/cwZEX3JTjl64/?ref=app
4 ответов
+ 2
max() doesn't know what a is. Because a is defined in main(). In other words, a lives in main(), not in max(). You can pass a to max() by adding an int parameter.
+ 6
Akash , you must know the scope of variables.
Here variable a which is of int type is defined inside the main method so it's visibility or scope is limited to only inside main method!!
int a is not accessible outside of main method.
if you try to access it outside from main method then an error is thrown.
Your code can work correctly if you define Variable a inisde Class and define it as static as shown below👇🏻
class Program {
static int a= 1;
public static void main(String[ ] args) {
System.out.println(max());
}
static int max() {
return a;
}
}
Or you can do as stated by CarrieForle
0
If you declare the method then use the method to return the value. So in your case pass the value to the method max(a) then method compute and return the result.