简体   繁体   中英

Increment counter and display as zero padded string in Java

Are there any existing utilities like Apache Commons StringUtils that make it easy to increment an integer, but output it as a zero padded string?

I can certainly write my own utilizing something like String.format("%05d", counter) , but I'm wondering if there is a library that has this already available.

I'm envisioning something I can use like this:

// Create int counter with value of 0 padded to 4 digits
PaddedInt counter = new PaddedInt(0,4);

counter.incr();

// Print "0001"
System.out.println(counter); 

// Print "0002"
System.out.println(counter.incr());

String text = "The counter is now "+counter.decr();

// Print "The counter is now 0001"
System.out.println(text);

I doubt you'll find anything to do this, because padding and incrementing are two basic operations that are unrelated, and trivial to implement. You could have implemented such a class three times in the time you took to write your question. It all boils down to wrapping an int into an object and implementing toString using String.format .

In case anyone is interested, I threw together this a few minutes after posting my question:

import org.apache.commons.lang.StringUtils;

public class Counter {

    private int value;
    private int padding;

    public Counter() {
        this(0, 4);
    }

    public Counter(int value) {
        this(value, 4);
    }

    public Counter(int value, int padding) {
        this.value = value;
        this.padding = padding;
    }

    public Counter incr() {
        this.value++;
        return this;
    }

    public Counter decr() {
        this.value--;
        return this;
    }

    @Override
    public String toString() {
        return StringUtils.leftPad(Integer.toString(this.value), 
                this.padding, "0");
        // OR without StringUtils:
        // return String.format("%0"+this.padding+"d", this.value);
    }
}

The only problem with this is that I must call toString() to get a string out of it, or append it to a string like ""+counter :

@Test
public void testCounter() {
    Counter counter = new Counter();
    assertThat("0000", is(counter.toString()));
    counter.incr();
    assertThat("0001",is(""+counter));
    assertThat("0002",is(counter.incr().toString()));
    assertThat("0001",is(""+counter.decr()));
    assertThat("001",is(not(counter.toString())));
}

To be honest, I think you are mixing different concerns. An integer is an integer with all the operations and if you want to output it padded with zeros that is different thing.

You might want to have a look at StringUtils.leftPad as an alternative of String.format .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM