简体   繁体   中英

Java - How to use a variable from a method when imported into the main class

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!

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

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.

变量P在方法getLower中定义,因此它是局部变量,无法在main方法中访问。您需要全局定义变量,以便方法都可以访问它。因此可以使其成为静态变量或简单变量

p是一个方法变量,这意味着,一旦方法返回就会被垃圾收集,所以你无法得到它,你可以只返回它的值并将它分配给调用函数中的局部变量

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM