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.

有帮助吗?

解决方案

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);
}

其他提示

Do like this

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

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

}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top