【问题标题】:Why my static variables' values change every time I call?为什么每次调用时我的静态变量的值都会发生变化?
【发布时间】:2014-02-21 16:44:21
【问题描述】:

每次我调用 MyClass 的 getIndex 静态方法时,都会在屏幕上打印“Index: 1”。我想增加或减少索引的值。我的代码有什么问题?

public class MyClass 
{
    public static int index=0;

    public static void getIndex()
    {
       index++;
       System.out.println("Index:"+index);
       if(index>10)
            index=0;
    }
}

【问题讨论】:

  • 你不应该在getter中增加index的值,事实上在getter方法中修改一个字段是很奇怪的。 IMO 你不应该把它作为static 字段,getIndex 方法也不应该是静态的。
  • getIndex();getIndex();getIndex(); 打印 1,2,3。嗯...我很困惑。
  • 制作indexprivate并重新编译您的代码,以检测客户端代码的意外修改。
  • 如何在主程序中使用getIndex()?
  • 如何多次调用该方法?

标签: java static static-methods static-members


【解决方案1】:

当我添加代码来调用您的示例时,它会按您的预期工作:

public class MyClass 
{
    public static int index=0;

    public static void getIndex()
    {
       index++;
       System.out.println("Index:"+index);
       if(index>10)
            index=0;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 12; i++) {
            getIndex();
        }
    }
}

印刷:

Index:1
Index:2
Index:3
Index:4
Index:5
Index:6
Index:7
Index:8
Index:9
Index:10
Index:11
Index:1

到控制台。所以你怎么称呼它一定是问题所在。

【讨论】:

  • 是的,问题是我如何调用该方法.. 谢谢。
【解决方案2】:

猜测:您在程序中只调用了一次getIndex(),但随后多次运行该程序。那是行不通的;变量值不会跨程序实例保留。每次启动程序时,index 都会重置为 0。在程序的单次运行中多次调用 getIndex(),您会看到它按预期递增。

【讨论】:

    猜你喜欢
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    相关资源
    最近更新 更多