題目:給一個不多於5位的正整數,要求:一、求它是幾位數,二、逆序打印出各位數字。
public class 第二十四題打印各位數字 { public static void main(String[] args) { // 請輸入一個5位以內的正整數
System.out.print("請輸入一個5位以內的正整數:"); Scanner in = new Scanner(System.in); int n = in.nextInt(); if (n < 0 || n > 1000000) { System.out.println("輸入有誤,請重新輸入"); } else { System.out.println("這個數為" + getDigits(n) + "位"); reversePrint(n); } in.close(); } // 獲取這個數的位數
public static int getDigits(int n) { int count = 0; // 記錄位數
while (n > 0) { if (n % 10 != 0) { count++; } n /= 10; } return count; } // 逆序打印
private static void reversePrint(int n) { System.out.print("逆序輸出: "); while (n > 0) { if (n % 10 != 0) { System.out.print(n % 10 +" "); } n /= 10; } } }