0

我实现了一个计数器方法,它总是返回一个递增的数字。但用户可以给出希望的格式、2 位、3 位或任何他想要的。格式是 String 的标准 String.format() 类型,例如%02dor %5d。当达到最大值时,计数器应重置为 0。

如何找出可以用给定格式表示的最大值?

int counter = 0;
private String getCounter(String format){
    if(counter >= getMaximum(format)){
        counter = 0;
    }
    else {
        counter++;
    }
    return String.format(format, counter);
}

private int getMaximum(String format){
    //TODO ???
    //Format can be %02d => should return 100
    //Format can be %05d => should return 100000

}
4

3 回答 3

2

尚未验证此代码,但与此类似的东西应该可以与错误检查到位

    String str = fullresultText.replace ("%", "").replace("d", "");
    maxVal = Math.pow (10, Integer.parseInt (str));
于 2013-10-01T07:17:13.510 回答
1

没有任何内置功能,而且我不知道有任何库可以做到这一点(我可能是错的)。请记住,如有必要,格式会扩展以避免丢失数字。例如

System.out.printf("%06d", 11434235);

将愉快地打印整个 8 位数字。

所以直接指定格式可能不是正确的方法。创建一个Counter类来封装所需的“里程表”行为。

public class Counter {
    private int width;
    private int limit;
    private String format;
    private int value=0;
    public Counter(int width, int value) { 
        this.width  = width; 
        this.limit  = BigInteger.valueOf(10).pow(width).intValue()-1; 
        this.format = String.format("%%0%dd",width);
        this.value  = value;
    }
    public Counter(int width) {
        this(width,0);
    }
    public Counter increment() { 
        value = value<limit ? value+1 : 0;
        return this; 
    }
    @Override
    public String toString() {
        return String.format(this.format,this.value); 
    }
}

示例用法:

Counter c3 = new MiscTest.Counter(3,995);
for (int i=0; i<10; i++)
{
    System.out.println(c3.increment().toString());
}

输出:

996
997
998
999
000
001
002
003
004
005
于 2013-10-01T07:17:40.230 回答
1
private int counter = 0;

private String getCounter(String format) {
    counter = (counter + 1) % getMaximum(format);
    return String.format(format, counter);
}

private int getMaximum(String format) {
    try {
        MessageFormat messageFormat = new MessageFormat("%{0,number,integer}d");
        int pow = ((Long) messageFormat.parse(format)[0]).intValue();
        return (int) Math.pow(10, pow);
    } catch (ParseException e) {
        System.out.println("Incorrect format");
        return -1;
    }
}
于 2013-10-01T07:44:57.897 回答