Is there any way to generate ID combined with alphabets in java?

拥有回忆 提交于 2019-12-14 04:11:38

问题


I have created a students registration project and I need to give registration number on my own for those who are registering in my website. My Registration Id should be ABC0000001 so on. I tried this following code to generate reg no.

 for(int i=0000001;i<3;i++){

  System.out.println("ABC"+i);

}

But I got output as ABC1 ABC2 ABC3. This is not needed. Please advice.


回答1:


Numbers do not have significant leading zeros. (Never mind that the code actually uses an octal number literal in Java.)

See String.format and the Format Syntax. In particular, '0' flag, width modifier, and the 'd' (decimal integer) conversion are useful here.

for(int i=1; i<3; i++){
  // % - start of format
  // 0 - 0-pad the result
  // 7 - set result width to 7 characters wide
  // d - display as decimal integer
  String id = String.format("ABC%07d", i);
  System.out.println(id);
}



回答2:


Do like this

for(int i=1;i<3;i++){

  System.out.println("ABC00000"+i);

}


来源:https://stackoverflow.com/questions/21720130/is-there-any-way-to-generate-id-combined-with-alphabets-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!