I wrote a program for a college assignment, and I'd like to receive some pointers on making my code a little more efficient.
The program should ask the end user to enter an integer. Use the
isPalidrome
method to invoke the reverse method, and report whether the integer is a palindrome. Any one-digit integer or negative integer should be rejected with the specific error message (negative or one digit), and then the program should ask the user to re-enter the integer. Hint: To reverse the digits of a number, try this routine:int result = 0; while (number != 0) { // e.g. number = 123 // Iteration 1 Iteration 2 Iteration 3 int remainder = number % 10; // remainder = 3 remainder = 2 remainder = 1 result = result * 10 + remainder; // result = 3 result = 32 result = 321 number = number / 10; // number = 12 number = 1 number = 0 } // result contains the reverse of number
My solution:
package lab07;
import java.util.Scanner;
public class Lab07 {
public static int reverse(int number){
int result = 0;
while (number !=0){
int remainder = number % 10;
result = result * 10 + remainder;
number = number / 10;
}
return result;
}
public static boolean isPalindrome(int input){
int Palindrome = reverse(input);
if (Palindrome == input){
return true;
}
else
return false;
}
public static void main(String[] args) {
int integer = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter a positive, multi-digit integer: ");
integer = input.nextInt();
while (integer <= 9 && integer > 0)
{
System.out.println(integer + " is a single digit. Please re-enter another integer: ");
integer = input.nextInt();
if (isPalindrome(integer) && (integer > 0 && integer > 9))
{
System.out.println(integer + " is a palindrome");
return;
}
else if (!isPalindrome(integer) && (integer > 0 && integer > 9))
{
System.out.println(integer + " is not a palindrome");
return;
}
}
while (integer < 0)
{
System.out.println(integer + " is negative. Please re-enter another integer: ");
integer = input.nextInt();
if (isPalindrome(integer) && (integer > 0 && integer > 9))
{
System.out.println(integer + " is a palindrome");
return;
}
else if (!isPalindrome(integer) && (integer > 0 && integer > 9))
{
System.out.println(integer + " is not a palindrome");
return;
}
while (integer <= 9 && integer > 0)
{
System.out.println(integer + " is a single digit. Please re-enter another integer: ");
integer = input.nextInt();
if (isPalindrome(integer) && (integer > 0 && integer > 9))
{
System.out.println(integer + " is a palindrome");
return;
}
else if (!isPalindrome(integer) && (integer > 0 && integer > 9))
{
System.out.println(integer + " is not a palindrome");
return;
}
}
}
while (integer > 9){
if (isPalindrome(integer) && (integer > 0 && integer > 9))
{
System.out.println(integer + " is a palindrome");
return;
}
else if (!isPalindrome(integer) && (integer > 0 && integer > 9))
{
System.out.println(integer + " is not a palindrome");
return;
}
}
}
}