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 ?
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 ?
int には形式がありません。それらは数字です。文字列にはフォーマットがあります。NumberFormat または DecimalFormat を使用して数値をフォーマットできます。
これはフォーマットの問題です。id が数値の場合、Empolyee.toString() または同様の関数を使用して、必要に応じて id をフォーマットできます。
String.format("%02d", id);
IDを2か所にゼロで埋めます
int は常に「1」として保存されます。「01」として表示したい場合は、次のようなものを使用できます
public static void main(String[] args) {
int i = 2;
DecimalFormat twodigits = new DecimalFormat("00");
System.out.println(twodigits.format(i));
}
出力:
02
10 進数形式を使用できます
int の代わりに String を使用します。
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);
}
もちろん、メソッドが必要ですsetEmpId(String s)。