0

This loop inserts employee Ids like 1, 2, 4,.. 30.

for(int i=01;i<31;i++){
  Employee e = new Employee();
  e.setEmpId(i);
  aList.add(e);
}

However, I require the ids in the format 01, 02, 03 .. so on. Is there a simple way I can achieve this ?

happybuddha
  • 1,271
  • 2
  • 20
  • 40

5 Answers5

5

ints don't have a format. They're numbers. Strings have a format. You can format a number using NumberFormat or DecimalFormat.

Eric Stein
  • 13,209
  • 3
  • 37
  • 52
  • Thanks for the insight. I wonder how else could I convey that I want the integers format to be different than what I got. – happybuddha Aug 21 '13 at 15:25
4

This is more of a formatting issue. If the id is a number, the Empolyee.toString() or some similar function can format the id however you want.

String.format("%02d", id);

Will zero padd the id to 2 places for you

dkatzel
  • 31,188
  • 3
  • 63
  • 67
3

The ints will always be saved as '1'. If you want to display it as '01' then you can use something like this

public static void main(String[] args) {
    int i = 2;
    DecimalFormat twodigits = new DecimalFormat("00");
    System.out.println(twodigits.format(i));
}

Output:

02
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
0

You can use the Decimal Format

Add leading zeroes to number in Java?

Community
  • 1
  • 1
VortexMath396
  • 66
  • 1
  • 4
0

use String instead of int.

String istr = "";
for(int i=01;i<31;i++){
  Employee e = new Employee();
  if( i<10 )
    istr = "0" + i;
  else
    istr = "" + i;

  e.setEmpId(istr);
  aList.add(e);
}

of course you will need to have setEmpId(String s) method.

MrSimpleMind
  • 7,890
  • 3
  • 40
  • 45