1

I need to generate a sequence as follows:

PAY000000 - The first three characters(PAY) remain the same and the 000000 should be incremented by one:

I have tried the following method to generate a sequence number:

   public String generateSequence(String currentPayment) {

        String chunkNumeric = currentPayment.substring(3, 9);
        return "PAY" + (Integer.parseInt(chunkNumeric) + 1);

    }

Expected:

currentPayment: PAY000000  Expected value: PAY000001
currentPayment: PAY000001  Expected value: PAY000002

Actual Result:

currentPayment: PAY000001  Actual value: PAY2

The issue is when I pass PAY000001 as parameter the Integer.parseInt(chunkNumeric) remove all the leading zeros that is PAY2 generated instead of PAY000002.

Any idea how I can increment the string while keeping the leading zero?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
user1999453
  • 1,297
  • 4
  • 29
  • 65

1 Answers1

1

You should instead maintain the sequence as a number, i.e. an integer or long, and then format that number with left padded zeroes:

public String generateSequence(int paymentSeq) {
    return "PAY" + String.format("%06d", paymentSeq);
}

int seq = 1;
String nextSeq = generateSequence(seq);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 1
    I wonder if `return String.format("PAY%06d", paymentSeq);` would make any difference to your solution. May depend on how frequently this method is used. – deHaar Oct 05 '21 at 07:45
  • @deHaar Your version doesn't make much sense (at least to me). No need in converting from string to int, then back to string again. – Tim Biegeleisen Oct 05 '21 at 07:46
  • Yes, that's nonsense, I corrected the comment already ;-) Was the code OP posted. The only difference I am thinking about is the inclusion of `"PAY"` into the `String` passed to `String.format` – deHaar Oct 05 '21 at 07:47