我正在尝试使用我在主部分的另一个类中创建的方法中的变量。
例如:
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);
}
}
但是,我收到错误消息“p 无法解析为变量”。
我想做的事情可能吗?
提前致谢!
最佳答案
p
是 getLower
方法中的本地变量。您不是“导入”该方法 - 您只是调用它。当该方法返回时,该变量甚至不再存在。
您可以考虑从该方法返回 p
的值:
public int getLower() {
int p = 12;
// Do whatever you want here
return p;
}
然后将返回值赋给main
中的局部变量:
int result = example.getLower();
System.out.println(result);
您应该阅读Java tutorial on variables有关不同类型变量的更多信息。
关于Java - 当导入到主类中时如何使用方法中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21365098/