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

时间:2013-10-01 06:25:02

标签: java variables methods

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

5 个答案:

答案 0 :(得分:4)

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

所以请选择instance members,您可以在方法之间分享。

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

scope

考虑,

 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);
   }

答案 1 :(得分:3)

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

你可以这样做:

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教程。

相关问题