JAVA **6.3 Using multiple methods ( 10 points ): Palindromes are numbers or word
ID: 3739497 • Letter: J
Question
JAVA **6.3 Using multiple methods (10 points): Palindromes are numbers or words that are same when read from either end. Eg. Avid diva, civic, 12321, 52925. Write a java program PalindromeByMethods.java that reads in an integer number (any number of digits up to 10 digits) from user input. The program then passes this number on to a method called reportIfPalindrome( ) that returns a boolean value. The method reportIfPalindrome( ) makes a call to another method called reverseNum(int number) that returns the reverse of the original integer back to the reportIfPalindrome( ) method. Based on the original integer and its reversed value received from the reverseNum( ) method, the reportIfPalindrome( ) method decides if the number is a palindrome and passes this information back (a Boolean value) to the main( ) method. Based on the returned value, the main( ) method prints if or not the number is a palindrome. [If you wrote a numOfDigits( ) method for the last program, it will be useful for this program too.]
.
Sample Run 1
This program checks if a user-entered number is a palindrome. Please enter the number: 1234
Printed from main( ):
The number entered is: 1234
Making a call to reportIfPalindrome ( ) Now in method reportIfPalindrome ( )
The number received from main( ) is: 1234 Passing the number to reverseNum( ) Result received from reverseNum( )
The reverse of the received number 1234 is 4321. Reporting my decision back to main( )
Back in main( )
The number 1234 is NOT a Palindrome.
Explanation / Answer
// coding
import java.util.Scanner;
public class Palindrome
{
boolean reportIfPalindrome(int n)
{
int rec=reverseNum(n);
if(n==rec)
{
return true;
}
else
{
return false;
}
}
int reverseNum( int y)
{
int sum=0;
while(y>0)
{
int r=y%10;
sum=sum*10+r;
y=y/10;
}
return sum;
}
public static void main(String args[])
{
Palindrome ob=new Palindrome();
Scanner s =new Scanner(System.in);
System.out.print("Please enter a number :");
int number=s.nextInt();
System.out.println("The number entered is:" + number);
boolean ans=ob.reportIfPalindrome(number);
if(ans==true)
{
System.out.println("The number"+number+"is a Palindrome ");
}
else
{
System.out.println("The number"+number+"is NOT a Palindrome ");
}
}
}
//output 1:
Please enter a number :1331
The number entered is:1331
The number1331is a Palindrome
output 2:
Please enter a number :12345
The number entered is:12345
The number12345is NOT a Palindrome
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.