1. 程式人生 > >JAVA迴圈使每次迴圈出來的都是四位數例如0001,0002,0003 三種實現方式

JAVA迴圈使每次迴圈出來的都是四位數例如0001,0002,0003 三種實現方式

問題描述:迴圈使每次迴圈出來的都是四位數例如0001,0002,0003
現在給出三種實現方式:
第一種實現方式:

public class temp1 {

    public static void main(String[] args) {

        for (int i = 1; i <= 1000; i++) {
            if (i < 10) {
                System.out.println("000" + i);
            } else if (i < 100) {
                System.out.println("00"
+ i); } else if (i < 1000) { System.out.println("0" + i); } else { System.out.println(i); } } } }

第二種方式:

public class temp2 {

    public static void main(String[] args) {

        for (int i = 1; i <= 1000; i++) {
            String s = String.valueOf(i);
            if
(s.length() == 1) { System.out.println("000" + i); } else if (s.length() == 2) { System.out.println("00" + i); } else if (s.length() == 3) { System.out.println("0" + i); } else if (s.length() == 4) { System.out
.println(i); } } } }

第三種方式:

public class tem {

    public static void main(String[] args) {

        String str = "";
        for (int i = 1; i < 10000; i++) {
            str = String.format("%04d", i);
            System.out.println(str);
        }

    }

}