知识点:
1. 复用提取整数的各个位数 (Separating the Digits in an Integer) 中的方法
(http://blog.csdn.net/hpdlzu80100/article/details/51671536)
2. 尝试了两种复用方式:
1)调用外部类的方法
2)复制该方法到本测试类
看似一个小功能,实际写起来还挺有意思的!
代码如下:
//JHTP Exercise 4.30:Palindromes
//by pandenghuang@163.com
/**(Palindromes) A palindrome is a sequence of characters that reads the same backward as forward.
*For example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554
*and 11611. Write an application that reads in a five-digit integer and determines whether it’s a palindrome.
*If the number is not five digits long, display an error message and allow the user to enter
*a new value.*/
import java.util.Scanner;
public class PalindromesTest {
public static void main (String[] args){
Scanner input=new Scanner(System.in);
int[] result={};
System.out.print("请输入五位数的整数(输入-1退出):");
int number=input.nextInt();
while(number!=-1){
while (number<10000||number>99999){
System.out.println("您输入的数字不在范围内,请重新输入:");
number=input.nextInt();
}
result=extractDigit(number);
if (result[0]==result[4] && result[1]==result[3])
System.out.printf("%d是回文数\n",number);
else
System.out.printf("%d不是回文数\n",number);
System.out.print("请输入五位数的整数(输入-1退出):");
number=input.nextInt();
}
}
public static int[] extractDigit(int number){
int[] result=new int[5];
result[0] =number/10000; //获取万位数
result[1]=number%10000/1000; //获取千位数
result[2]=number%1000/100; //获取百位数
result[3]=number%100/10; //获取十位数
result[4]=number%10; //获取个位数
return result;
}
}
运行结果:
请输入五位数的整数(输入-1退出):12345
12345不是回文数
请输入五位数的整数(输入-1退出):12321
12321是回文数
请输入五位数的整数(输入-1退出):123456
您输入的数字不在范围内,请重新输入:
65856
65856是回文数
请输入五位数的整数(输入-1退出):-1