【问题标题】:Change static variables更改静态变量
【发布时间】:2014-12-01 15:21:08
【问题描述】:

我想知道是否可以更改下面的代码,使第二个输出打印我得到“2.2noo100onn”而不是“1.1foo200oof”的更改变量?

是否可以从不同类型返回多种类型,或者有什么方法可以创建一个混合变量类型数组?

我正在处理的代码要大得多,但这个示例的工作方式相同。

public class test 
{
    static String s1 = "foo";
    static String s2 = "oof";
    static double d1 = 1.1;
    static int i1 = 200;

       public static void main (String[] args)
       {
            // Ausgabe Hello World!
            System.out.println(d1+s1+i1+s2);

            bla();
            System.out.println(d1+s1+i1+s2);
       }

    public static void bla() {
         String s1 = "noo";
         String s2 = "onn";
         double d1 = 2.2;
         int i1 = 100;
    }
}

【问题讨论】:

    标签: java variables static


    【解决方案1】:

    是的,你可以。

    在方法 bla() 中,您正在重新声明变量,以便新变量具有本地范围。它们实际上是与您在类开始时声明和初始化的变量不同的变量。相反,以这种方式操作类范围变量:

    public static void bla() {
         s1 = "noo";
         s2 = "onn";
         d1 = 2.2;
         i1 = 100;
    }
    

    【讨论】:

      【解决方案2】:

      如果您希望 bla 方法更改静态变量,请不要隐藏它们。当您在该方法中重新声明这些变量时,您正在创建新的局部变量,这些变量仅存在于该方法的范围内。

      将您的代码更改为:

      public static void bla() 
      {
           s1 = "noo";
           s2 = "onn";
           d1 = 2.2;
           i1 = 100;
      }
      

      【讨论】:

        【解决方案3】:
        public static void bla() {
             String s1 = "noo"; //s1 is a local variable that's never used
             String s2 = "onn";
             double d1 = 2.2;
             int i1 = 100;
             //s1, s2, d1 and i1 will be destroyed and garbage collected here
        }
        

        您正在声明一个新的字符串对象并隐藏类成员s1 这里的 String 不是类成员。

        【讨论】:

          【解决方案4】:

          试试这个.....

          public class test 
          {
              static String s1 = "foo";
              static String s2 = "oof";
              static double d1 = 1.1;
              static int i1 = 200;
          
                 public static void main (String[] args)
                 {
                       // Ausgabe Hello World!
                       System.out.println(d1+s1+i1+s2);
          
                      bla();
                       System.out.println(d1+s1+i1+s2);
                 }
          
                 public static void bla() 
                 {
                     s1 = "noo";
                     s2 = "onn";
                     d1 = 2.2;
                     i1 = 100;
                 }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2016-03-27
            • 1970-01-01
            • 1970-01-01
            • 2013-04-01
            • 2018-06-22
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多