Here you can find the source of incrementAlpha(String suppliedPrefix, String lastNumber, int numberLength)
Parameter | Description |
---|---|
prefix | - if the sequence value has a known prefix before the number, eg INV0001 has a prefix of "INV" |
numberLength | - the minimum length of the number when specified as a string |
lastNumber | - the number to increment |
Parameter | Description |
---|---|
Exception | general Exception |
public static String incrementAlpha(String suppliedPrefix, String lastNumber, int numberLength) throws Exception
//package com.java2s; //License from project: LGPL import java.util.Formatter; public class Main { /**/*w ww . j a v a 2 s . co m*/ * Returns the next alpha value - ie A00A1 becomes A00A2 etc * * @param prefix * - if the sequence value has a known prefix before the number, * eg INV0001 has a prefix of "INV" * @param numberLength * - the minimum length of the number when specified as a string * @param lastNumber * - the number to increment * @return - the next number * @throws Exception * general Exception */ public static String incrementAlpha(String suppliedPrefix, String lastNumber, int numberLength) throws Exception { String newNumber = ""; String nonNumeric = lastNumber; Integer value = new Integer(1); String prefix; if (suppliedPrefix != null) { prefix = suppliedPrefix; } else { prefix = ""; } if (lastNumber != null) { String[] parts = (new StringBuilder(" ").append(lastNumber)).toString().split("\\D\\d+$"); //cater for alpha prefix if (parts.length > 0 && parts[0].length() < lastNumber.length()) { String numberPart = lastNumber.substring(parts[0].length(), lastNumber.length()); nonNumeric = lastNumber.substring(0, parts[0].length()); value = new Integer(Integer.parseInt(numberPart) + 1); //cater for purely numeric prefix } else if (prefix.matches("^\\d+$") && lastNumber.matches("^\\d+$") && !"0".equals(lastNumber)) { int len = prefix.length(); value = new Integer(Integer.parseInt(lastNumber.substring(len)) + 1); nonNumeric = prefix; //cater for numeric only } else if (lastNumber.matches("^\\d+$")) { nonNumeric = prefix; value = new Integer(Integer.parseInt(lastNumber) + 1); } } else { nonNumeric = prefix; } // now put prefix and value together int newLength = (nonNumeric.length() + value.toString().length() > numberLength ? nonNumeric.length() + value.toString().length() : numberLength); StringBuilder sb = new StringBuilder(newLength + 1); try (Formatter f = new Formatter(sb)) { newNumber = nonNumeric + f .format(new StringBuilder("%1$").append(newLength - nonNumeric.length()).append("s").toString(), value.toString()) .toString().replace(" ", "0"); } return newNumber; } }