Increase number with character in Java

Thiện :

I have a problem with increasing number and character combinations. What I want is increase from 001 to ZZZ

Example: 001, 002,..., 999, 00A,..., 00Z, 0AA,..., ZZZ

My code look like this:

int numberA = 1000;
int numberB = 1024;
int numberC = 1025;

/*
 * Some formulae here
 */

System.out.println(numberA);
//Result: 00A
System.out.println(numberB);
//Result: 00Z
System.out.println(numberC);
//Result: 0A0

Are there any fomulae to solve this problem?

Roland :

Maybe the following will help you get started ;-)

final Integer radix = 36; // that's 0-9 A-Z
final Double limit = Math.pow(radix.doubleValue(), 3.0 /* max number of 'chars' */);
Stream.iterate(0, i -> i+1)
        .map(i -> Integer.toString(i, radix))
        .map(s -> String.format("000%S", s)
                        .substring(s.length())) // leading 0, uppercase
        .limit(limit.longValue())
        .forEach(System.out::println);

Or simply:

String radix36 = Integer.toString(yourIntThatYouCanIncrement, 36);

Of course if you require the 00#-format (leading zeros and uppercase) you need to apply that functions too. Holgers comment already contains a short variant of it to combine uppercase/leading zeros:

String formatted = String.format("000%S", radix36)
                         .substring(radix36.length());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112758&siteId=1