[英]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'. 但是,我收到错误消息'p无法解析为变量'。
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
. 不,除非你以声明n
方式声明p
。
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: 在您的示例中, n
变量仅存在于getLower()
方法中,其他方法无法访问它,因此您必须在类级别声明它:
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);
}
}
p
is a local variable within the getLower
method. p
是getLower
方法中的局部变量。 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: 您可以考虑从方法返回p
的值:
public int getLower() {
int p = 12;
// Do whatever you want here
return p;
}
Then assign the return value to a local variable in main
: 然后将返回值赋给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. 您应该阅读有关变量的Java教程,以获取有关不同类型变量的更多信息。
变量P在方法getLower中定义,因此它是局部变量,无法在main方法中访问。您需要全局定义变量,以便方法都可以访问它。因此可以使其成为静态变量或简单变量
p是一个方法变量,这意味着,一旦方法返回就会被垃圾收集,所以你无法得到它,你可以只返回它的值并将它分配给调用函数中的局部变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.