如何在每次执行后减少java中声明的变量的值

时间:2016-07-21 18:14:14

标签: java constants

public class test {
    public static void main() {
        i = 5;
        i--;
        System.out.println("The value of i is" + i);
    }
}

在上面的程序中,我想要常量i的值,在每次执行程序后都会减少,但它不会发生也不会发生。有没有办法可以减少声明的常量i的值?

3 个答案:

答案 0 :(得分:0)

你不能这样做....

使用java首选项,您可以存储该值并在每次应用程序启动时再次读取它...

 void main(){
        i = getValueFromPreferences();
        i--;
        System.out.println("The value of i is"+i);
    }

实施例

String key = "myCounter";
//method for writing
public void setPreference(final int newVal) {
    Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
    prefs.putInt(key, newVal);
}

//method for reading back 
public int getValue(){
    Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
    return prefs.getInt(key, -1);
}

答案 1 :(得分:0)

你必须将我存储在java之外。

  1. 在环境变量中
  2. 在档案中
  3. 在数据库中
  4. 获取初始值作为参数,并返回i + 1作为下次执行的退出代码

答案 2 :(得分:0)

Try this code:

public class Test {
    private static int i = 5;
    static void main() {
        i--;
        System.out.println("The value of i is" + i);
    }

    public static void main(String[] args) {
     Test test = new Test();
     test.main();
     test.main();
     test.main();
    }

}