(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.
5 Digit Integer Palindrome in Java
/*
* Filename: NumericalPalindrome.java
*
* Description: Exercise 4.30 - Palindromes
*
* @Author: Bilal Tahir Khan Meo
* Website: https://codeblah.com
*
* =====================================================================================
*/
public class NumericalPalindrome{
// ensure number is of length 5
public boolean validate(int value){
return (Integer.toString(value).length() == 5);
}
public boolean isPalindrome(int value){
int arrValue[] = new int[5];
// split the int
// countdown so as to not reverse the original order
for(int i=4; i>=0; i--){
arrValue[i] = value % 10;
value /= 10;
}
return ((arrValue[0] == arrValue[4]) && (arrValue[1] == arrValue[3]));
}
}
NumericalPalindromeTest.java
/*
* Filename: NumericalPalindromeTest.java
*
* Description: 4.30 - determine whether a 5 digit number is a palindrone
*
* @Author: Bilal Tahir Khan Meo
* Website: https://codeblah.com
*
* =====================================================================================
*/
import java.util.Scanner;
public class NumericalPalindromeTest{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
NumericalPalindrome np = new NumericalPalindrome();
while(true){
System.out.print("Enter a 5 digit number to test: ");
int testCase = sc.nextInt();
if(np.validate(testCase)){
if(np.isPalindrome(testCase))
System.out.printf("%s is a palindrone.\n", testCase);
else
System.out.printf("%s is not a palindrone.\n", testCase);
break;
}
}
}
}