2014-03-26 26 views
0

我必須存儲的用戶ID類似的標號附加要求:需要存儲與數字用戶ID追加在Java中

如果用戶ID是「計算器」,ID「stackov」的那麼前7個字母取,如果它不在DataBase中,那麼它應該存儲爲「stackov001」。

現在,如果其他用戶給的「stackoverflowed」,那麼它的用戶ID應被存儲爲因爲

我用子試過這種「stackov002」但我不能夠得到「00」類似的用戶ID。我能夠獲得「stackov1」「stackov2」但不是「stackov001」。

請soemone幫忙。

+2

代碼比英文好。 – Maroun

+0

這個問題似乎是無關緊要的,因爲它沒有提供足夠的研究工作,也沒有提供任何代碼。 – skiwi

+0

@MarounMaroun誰說這個詞?但我同意:D – Cataclysm

回答

0
String produceIdMethod(String input){ 

     String sub = input.substring(0, 7);//sub has 1st 7 characters 

     //now fire a db query as select columnnameforid from table where columnnameforid like ':sub%' order by columnnameforid asc; 
     //and set sub dynamically using setparameter. it should give list of ids in ascending order 
     //get last value of the list and lets say it as strDB 
     if(retrived list is null or empty) 
      return sub+"001"; 

     String temp = strDB.substring(7, strDB.length);//get only digits in id 
     Integer i = Integer.parseInt(temp);//convert it to list 
     i=i+1;//increment it 
     if(i < 10) { 
      return sub+ "00" + i;//prefix 00 if its single digit value 
     } 
     if(i < 100) { 
      return sub+ "0" + i;prefix 0 if its double digit value 
     } 
     return sub+ index;//otherwise return as it is } 
+0

謝謝..它工作.. – user1782009

+0

其確定歡迎.. –

0

假設你已經有部分用戶名(前7個字符)和正確的指標,那麼就做這樣的事情:

public String createUsername(final String partialUsername, final int index) { 
    if(index < 10) { 
     return partialUsername + "00" + index; 
    } 
    if(index < 100) { 
     return partialUsername + "0" + index; 
    } 
    return partialUsername + index; 
} 
+0

INDEX在這裏的價值是什麼? – user1782009

+0

無論你的序列號是什麼。你說你有7個字符的部分用戶名,那麼你說你可以根據用戶名是否在數據庫中來計算索引,所以這段代碼簡單地將兩個用戶填充到一起。 –

0

嘗試一下本作填充:

String userId = "stackov"; 
int cnt = 1; 
userId = String.format("%s%03d",userId, cnt); 
System.out.println(userId); //stackov001 
0

簡單:

public static String generate(String userId,int index){ 
    String partialUserId=userId.substring(0,7); 
    String idxString=String.format("%03d", index); 
    return (partialUserId+idxString); 
} 

假定你通過id大於7的長度,否則會拋出一個例外。

+0

這裏的索引值是多少? – user1782009

+0

您可以保留一個計數器爲 –