user412308 - 7 months ago 35
Java Question

# Java: String index out of range while checking if a number is a palindrome

So, in order to check if a number is a palindrome I converted it to a string. I know there is a similar question on SO but I have already checked that solution, so any help would be appreciated.
Why do I get a

?

My code is here;

/*
(Palindrome integer) Write the methods with the following headers

// Return the reversal of an integer, i.e., reverse(456) returns 654
public static int reverse(int number)

// Return true if number is a palindrome
public static boolean isPalindrome(int number)

Use the reverse method to implement isPalindrome. A number is a palindrome
if its reversal is the same as itself. Write a test program that prompts the
user to enter an integer and reports whether the integer is a palindrome.
*/

import java.util.Scanner;

public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = input.nextInt();
if (isPalindrome(number))
System.out.println("The number is a palindrome");
else
System.out.println("The number is not a palindrome");

}

public static int reverse(int number) {
String reverse = "";
String n = number + " ";
for (int i = n.length() - 1; i >= 0; i--) {
reverse += n.charAt(i);
}

return Integer.parseInt(reverse);
}

public static boolean isPalindrome(int number) {
return number == reverse(number) ? true : false;
}
}

The problem is in the reverse function. in fact the instruction String n = number + " "; is the concatenation of the value number with a blank string. This is not a number and later on gives NomberFormatException at the instruction return Integer.parseInt(reverse); . You should use String n = Integer.toString(number);

Here's the reviewed method

public static int reverse(int number) {
String reverse = "";
String n = Integer.toString(number); // + " ";
System.out.println(reverse);
for (int i = n.length() - 1; i >= 0; i--) {
reverse += n.charAt(i);
}

return Integer.parseInt(reverse);
}