0

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

4

5 回答 5

4

在方法中创建的变量是方法的局部变量,作用域仅限于方法。

所以去吧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(String param){
    System.out.println("    " + param);
}
于 2013-10-01T06:27:23.050 回答
4

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

于 2013-10-01T06:26:20.073 回答
1

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

于 2013-10-01T06:30:08.043 回答
0

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

于 2013-10-01T06:37:54.553 回答
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;
}

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

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

于 2013-10-01T07:28:57.633 回答