85.4k views
1 vote
Implement a Java program using simple console input & output and logical control structures such that the program prompts the user to enter a 5 digit integer as input and does the following tasksThe program checks whether the input number is a palindrome or not and prints the result of this palindrome check. A number is a palindrome if it reads the same backward as forward. For example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554 and 11611; whereas 12312, 55565, 45545 and 11621 are not a palindrome. Your program should print "The number is palindrome" or "The number is not palindrome" after checking the input number.The program checks whether the input number has 5 digits or not and prints the error message "Invalid number" if the input number is not a 5 digit one.I posted my code below, I think I have a good start with reversing the number but I'm not sure how to implement the portion of how to actually check if it is a palindrome.import java.util.Scanner;public class Problem2 {public static void main(String[] args){int number;

Scanner scanner = new Scanner(System.in);System.out.println("Enter a positive integer between 1 and 5 digits long that you would like to test for a palindrome: ");num = in.nextInt();for( ;num != 0; ){reversenum = reversenum * 10;reversenum = reversenum + num%10;num = num/10;

1 Answer

2 votes

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.

User Pavel Chuchuva
by
4.3k points