【问题标题】:how to increment value of string variable?如何增加字符串变量的值?
【发布时间】:2015-05-26 12:20:05
【问题描述】:

我必须增加变量计数并返回为 001, 002...,099....,999 update() 返回计数值,reset() 将重置静态变量 我用过的代码。

public class getCount {
static String count="0";
//resets the value to 0
public static void reset() {
    // TODO Auto-generated method stub
    count="0";
}
//updates the value
public static String update() {
    String temp=count;
    DecimalFormat df1 = new DecimalFormat("000");
    String T=String.valueOf(df1.format(Integer.parseInt(temp)));    
    if( temp=="1000")
    {
        count="1";
        return count;
    }
    return T;
}

//main() is used for testing    
public static void main(String[] a) {
    String c1=update();
    System.out.println(c1);

    String c2=update();
    System.out.println(c2);

    String c3=update();
    System.out.println(c3);

    String c4=update();
    System.out.println(c4);

    String c5=update();
    System.out.println(c5);

    reset();
    String c6=update();
    System.out.println(c6);
    String c7=update();
    System.out.println(c7);
    String c8=update();
    System.out.println(c8);
}

我得到的输出是 001,001....

【问题讨论】:

  • 在找出新字符串 (String T=String.valueOf(df1.format(Integer.parseInt(temp)));) 后,不要将其存储在任何地方。此外,if( temp=="1000") 不起作用:使用 .equals()
  • 除了出色的 khelwood 的评论之外,您为什么将您的计数器存储为 Stringint 在这里应该足够了,而且效率更高:)
  • 我没有看到你增加任何东西。将设置String T 的行更改为String T=String.valueOf(df1.format(Integer.parseInt(temp) + 1));
  • @khelwood 谢谢.. 但它不起作用:(
  • @Nizil 是的.. int 将服务于我的目的.. 但我必须在递增后将其返回为 001 、 002 等等

标签: java static


【解决方案1】:

简单一点:

public class Count {

    private static int count = 0;

    // resets the value to 0
    public static void reset() {
        count = 0;
    }

    // updates the value
    public static String update() {
        count++;
        if(count == 1000) count = 1;
        return String.format("%03d", count);
    }

    // main() is used for testing
    public static void main(String[] a) {

        for(int i=0; i< 1001; i++){
            String c1 = update();
            System.out.println(c1);
        }

        reset();

        String c2 = update();
        System.out.println(c2);

        String c3 = update();
        System.out.println(c3);


    }
}

顺便说一句,你的班级名称 getCount 应该是 GetCount 甚至更好(在我看来),没有动词:Count

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    相关资源
    最近更新 更多