0

常にインクリメントされた数値を返すカウンター メソッドを実装しました。ただし、ユーザーは希望する形式、2 桁、3 桁、または必要なものを指定できます。%02dフォーマットは、またはのような String の標準 String.format() 型です%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 に答える