(2)編寫一個Java應用程序。用戶從鍵盤輸入一個1—9999之間的數,程序將判斷這個數是幾位數,並判斷這個數是不是迴文數。迴文數是指將該數含有的數字逆序排列後獲得的數和原數相同,例如1212一、3223都是迴文數。java
如何從鍵盤輸入一個數呢?git
1 package test; 2 import java.util.Scanner; 3 public class KeyboardInput { 4 public static void main(String[] args){ 5 Scanner x = new Scanner(System.in);//構造一個Scanner對象,其傳入參數爲System.in 6 System.out.println("請輸入一個整數"); 7 int i = x.nextInt();//讀取一個int數值 8 System.out.println("你輸入的數字是:"+i); 9 } 10 }
1 package hi; 2 import java.util.Scanner; 3 public class Palindrome { 4 public static void main(String[] args){ 5 Scanner x = new Scanner(System.in);//構造一個Scanner對象,其傳入參數爲System.in 6 System.out.println("請輸入一個整數"); 7 int num= x.nextInt();//讀取一個int數值 8 int a1,a2,a3,a4,a5; 9 a5=num/10000; 10 a4=num%10000/1000; 11 a3=num%1000/100; 12 a2=num%100/10; 13 a1=num%10; 14 if(a5!=0){ 15 System.out.println(num+" is 5 digits"); 16 if(a5==a1&&a2==a4){ 17 System.out.println(num+" is a palindrome"); 18 }else{ 19 System.out.println(num+" is not a palindrome"); 20 } 21 } 22 else if(a4!=0){ 23 System.out.println(num+" is 4 digits"); 24 if(a1==a4&&a2==a3){ 25 System.out.println(num+" is a palindrome"); 26 }else{ 27 System.out.println(num+" is not a palindrome"); 28 } 29 } 30 else if(a3!=0){ 31 System.out.println(num+" is 3 digits"); 32 if(a1==a3){ 33 System.out.println(num+" is a palindrome"); 34 }else{ 35 System.out.println(num+" is not a palindrome"); 36 } 37 38 } 39 else if(a2!=0){ 40 System.out.println(num+" is 2 digits"); 41 if(a1==a2){ 42 System.out.println(num+" is a palindrom"); 43 44 } 45 else{ 46 System.out.println(num+" is not a palindrom"); 47 } 48 49 } 50 else if(a1!=0){ 51 System.out.println(num+" is 1 digits"); 52 System.out.println(num+" is a palindrom"); 53 } 54 else{ 55 System.out.println(num+" is not between 0 and 99999"); 56 } 57 58 } 59 }