Java

Generating Next ID when dealing with alpha numeric Ids(Project Development)


While working on any project  you deal with lot of ID's.
Sometime they are only numeric, sometime they are alpha-numeric,
 
When ID's are numeric it is easier to increment it , but when ID's are alpha numeric it becomes tough to increment it.

For example let say ID's are of format: JWZ00001


Now when we need to increment it to next ID i.e JWZ00002, we need to use String manipulation for it and then parse it and increment the value and again reconstruct it.
 
Let us do it step by step.
 

Step 1: Getting number from the query string.

String id="JWS00001";
id=id.replace("JWS","");
Using replace method of String will put off the String part and id variable now contains only "00001".


Step 2: Converting the String to int.

int x=Integer.parseInt(id);
After this step "00001" is parsed to an int value of 1.
Remember all the 0's are shelved off.

 

Step 3: Adding 1 in the number parsed.

x=x+1;

Step 4: Setting the String back.

 
When the number is parsed back to int, it will be 2 and not "00002" which is now required. So we need to construct the string back.
Let say the new string is going to be nextId;

String nextId="";

Given the length of the number we can use if block and construct it.

if(x>=1&&x<=9)
{
nextId="JWZ0000"+x;

}
if(x>=10&&x<=99)
{
nextId="JWZ000"+x;

}
if(x>=100&&x<=999)
{
nextId="JWZ00"+x;

}
if(x>=1000&&x<=9999)
{
nextId="JWZ0"+x;

}
if(x>=10000&&x<=99999)
{
nextId="JWZ"+x;

}

Here we complete the whole code.




class NextIdGeneration

{

 public static void main(String[] args)

 {

  String id="JWZ00001";

  id=id.replace("JWZ","");

  int x=Integer.parseInt(id);

  x=x+1;



  String nextId="";



  if(x>=1&&x<=9)

{

nextId="JWZ0000"+x;



}

if(x>=10&&x<=99)

{

nextId="JWZ000"+x;



}

if(x>=100&&x<=999)

{

nextId="JWZ00"+x;



}

if(x>=1000&&x<=9999)

{

nextId="JWZ0"+x;



}

if(x>=10000&&x<=99999)

{

nextId="JWZ"+x;



}



System.out.println(nextId);

}

}

 

 

Related Posts

Table Of Contents

;