java - 如何更新传递给方法的变量?

标签 java

<分区>

当我将变量传递给我的方法时,它们不会在主代码中更新,而只会传递给方法。一旦传递的变量将在主代码中更新,该怎么做?谢谢!

//////////// here is main code:
public static  class MyCoding extends MainScreen{ static int mee=1;
        public static void myCode(){

       Status.show("mee="+mee, 2000);   // shows me=1

       Moo.moo(mee);

       Status.show("mee="+mee, 2000);// should be mee=76547545 but still shows mee=1 !

    }
}


//////////// here is my method:

public static  class Moo extends MainScreen{
    public static void moo(int bee){
        mee=76547545;

        return;
    }
}

要做什么?谢谢!

最佳答案

传递原始数据类型参数

Primitive arguments, such as an int or a double, are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost.

传递引用数据类型参数

Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level.

要获得您期望的行为,您需要返回一个值并将其分配给原始变量。

mee = Moo.moo(mee);

在你的方法中:

public static int moo(int mee)
{
   // some processing
   mee += 76547545;

   return mee;
}

Passing Information to a Method or a Constructor

关于java - 如何更新传递给方法的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8514818/

相关文章:

java - NullpointerException 尝试调用虚拟方法 'void android.widget.Button.setOnClickListener

java - Protocol Buffer 3 : Enums as keys in a map

java - setTitle(字符串) - 黑莓

java - 在方法中设置textview文本

java - 是否可以创建一个开放式数组?

java - sbt:避免 java 子项目中的多个组装/发布步骤

java - 图像资源在 Android 中给出 0

java - 在服务层做一个 STATIC 方法有什么害处——Spring 3

java - 在 Java 中创建 Excel 图表

java - Apache Storm : InvalidTopologyException(msg:Component: [x] subscribes from non-existent component [y]