Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

Do like this

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

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

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top