如何在java中的方法之间传递变量?

在我的程序的主要方法中,我有一堆扫描仪输入,我已经使用参数传递给各种方法。 在那些各种方法中,我已经完成了计算,创建了新变量。 在我的最后一个方法中,我需要将这些新变量加在一起,但编译器不会识别新变量,因为它们只存在于其他方法中。 我如何将新变量传递给我的最终方法?

方法中创建的变量是方法本地的,范围仅限于方法。

所以去instance members ,你可以在方法之间分享。

如果声明,则不需要在方法之间传递,在方法中更新这些成员。

范围

考虑,

  public static void main(String[] args) { String i = "A"; anotherMethod(); } 

如果您尝试访问i,则会在以下方法中出现编译器错误,因为i是main方法的局部变量。 您无法使用其他方法访问。

  public static void anotherMethod(){ System.out.println(" " + i); } 

您可以做的是,将该变量传递到您想要的位置。

  public static void main(String[] args) { String i = "A"; anotherMethod(i); } public static void anotherMethod(int param){ System.out.println(" " + param); } 

而不是创建局部变量创建类变量。类变量的范围是它们是全局的意味着您可以在类中的任何位置访问这些变量

您可以创建一个List并将其作为参数传递给每个方法。 最后,您只需遍历列表并处理结果即可。

使用新变量创建一个对象,并返回它们的总和。 在您的方法中,使用此对象进行新变量计算。 然后使用object方法获取新变量的总和

你可以这样做:

 public void doStuff() { //Put the calculated result from the function in this variable Integer calculatedStuff = calculateStuff(); //Do stuff... } public Integer calculateStuff() { //Define a variable to return Integer result; //Do calculate stuff... result = (4+4) / 2; //Return the result to the caller return result; } 

您也可以这样做(然后您可以在类中的任何函数中检索变量calculatedStuff):

 public class blabla { private Integer calculatedStuff; public void calculateStuff() { //Define a variable to return Integer result; //Do calculate stuff... result = (4+4) / 2; //Return the result to the caller this.calculatedStuff = result; } } 

但正如其他人的建议,我也强烈建议你做一个基本的Java教程。