Answer:
import java.util.Scanner;
import java.util.regex.*;
public class Problem2 {
public static void main(String[] args)
{
int number;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a positive integer with exactly 5 digits long that you would like to test for a palindrome: ");
String str = scanner.nextLine();
int len = str.length();
if (!Pattern.matches("^[1-9]\\d{4}$", str)) {
System.out.println("Invalid number");
} else {
boolean isPalindrome = true;
for(int i=0; i<len/2; i++) {
if (str.charAt(i) != str.charAt(len-i-1)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println("The number is palindrome");
} else {
System.out.println("The number is not palindrome");
}
}
}
}
Step-by-step explanation:
Even though the problem talks about numbers, a palindrome check is more about strings, so that's how I'd handle it. I check the validity of the input using a regular expression (note how I don't allow the number to start with a zero, you can change that if you want), and then I check for palindrome to iterating to only halfway the string, and checking the i-th position ffrom the start against the i-th position from the end. If there is no match, the loop is aborted.
See that also for even-length palindromes this will work.