如何在Java中的方法之间传递变量? [英] How do I pass variables between methods in java?
问题描述
在程序的主要方法中,我有一堆扫描仪输入,已使用参数将其传递到各种方法中. 在那些不同的方法中,我进行了计算,创建了新的变量. 在我的最终方法中,我需要将这些新变量加在一起,但是编译器将无法识别新变量,因为它们仅存在于其他方法中.我该如何将新变量传递给我的最终方法?
In the main method of my program I have a bunch of scanner input which I have passed into various methods using parameters. In those various methods I have done calculations, creating new variables. In my final method I need to add those new variables together, but the compiler will not recognize the new variables because they only exist in those other methods. How would I go about passing the new variables to my final method?
推荐答案
Variables created in methods are local to methods and scope is restricted to methods only.
因此,请使用 instance members
可以在方法之间共享.
So go for instance members
, which you can share among methods.
如果这样声明,则不需要在方法之间传递它们,但是您可以在方法中访问和更新这些成员.
If you declare so, you don't need to pass them among methods, but you can access and update those members in methods.
考虑
public static void main(String[] args) {
String i = "A";
anotherMethod();
}
如果尝试访问i
,则在以下方法中会出现编译器错误,因为i
是main方法的局部变量.您无法使用其他方法访问.
You get a compiler error in the below method if you try to access i
, because i
is a local variable of the main method. You cannot access in other methods.
public static void anotherMethod() {
System.out.println(" " + i);
}
您可以做的是,将该变量传递到所需的位置.
What you can do is, pass that variable to where you want.
public static void main(String[] args) {
String i = "A";
anotherMethod(i);
}
public static void anotherMethod(String param){
System.out.println(" " + param);
}
这篇关于如何在Java中的方法之间传递变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!