Java - How to use a variable from a method when im

2019-09-06 19:52发布

问题:

I am trying to use a variable from a method I created in another class in the main section.

For example:

public class test {

public static int n;

public void getLower(){

    int p = 12;
}


public static void main(String[] args) {

    test example = new test();

    example.getLower();

    System.out.println(p);



}

}

However, I get the error message 'p cannot be resolved to a variable'.

Is what I'm trying to do possible?

Thanks in advance!

回答1:

p is a local variable within the getLower method. You're not "importing" the method - you're just calling it. When the method has returned, the variable no longer even exists.

You could consider returning the value of p from the method:

public int getLower() {
    int p = 12;
    // Do whatever you want here
    return p;
}

Then assign the return value to a local variable in main:

int result = example.getLower();
System.out.println(result);

You should read the Java tutorial on variables for more information about the different kinds of variables.



回答2:

Is what I'm trying to do possible?

No, unless you declare p the same way you are declaring n.

In your example, the n variable exists only in the getLower() method, it's not accessible by other methods, so you have to declare it at class-level:

public class test {

    public static int n;
    public static int p = 12;

    //.......
    public static void main(String[] args) {
        System.out.println(p);
    }
}

or

public class test {

    public static int n;
    public int p = 12;

    //.......
    public static void main(String[] args) {
        test t = new test();
        System.out.println(t.p);
    }
}

Read more about variable scope



回答3:

varaiable P is defined in the method getLower so it is local variable which cant be accessed in main method.You need to define the variable globally so that both the method can access it.So can make it static or simple variable



回答4:

p is a method variable, that means, it is garbage collected as soon as the method returns, so you can't get it, you can just return it's value and assign it to a local variable in the caller function