0

Im trying to make a simple programm that compares if a number or word is a palindrome. Ive made the following code, but I dont get why my if statement doesnt work. If you print the results you can see the numbers or letters are the same but my if statement doesnt think so. Here is my code. Thanks :

import java.util.*;
public class myPalindromo
  {
public static void main(String[] args)
{
    // TODO Auto-generated method stub  
    String number;  

    ArrayList < String > myNumber = new ArrayList < String > ();

    Scanner sn = new Scanner(System.in);
    number= sn.nextLine();

    for(int i = 0 ; i<number.length() ; i++)
    {
        myNumber.add(number.valueOf(number.charAt(i)));
    }

    for(int i = 0; i<myNumber.size(); i++)
    {

        System.out.println(myNumber.get(i)+"=="+myNumber.get((myNumber.size()-1)-i));

        if(myNumber.get(i)== myNumber.get((myNumber.size()-1)-i))
            System.out.println("palindrome");
        else
            System.out.println("not palindrome");


    }

}

}
Benjamin
  • 2,257
  • 1
  • 15
  • 24
Kevjumba94
  • 19
  • 2

3 Answers3

0

To check if a string is palindrome try this:

static boolean isPalindrome(String s) {
    int center = (int)s.length()/2 - 1;
    for (int i = 0; i <= center; i++) {
        if (s.charAt(i) != s.charAt(s.length() - i-1) )
            return false;
    }
    return true;
}
Mohsen Kamrani
  • 7,177
  • 5
  • 42
  • 66
0

You should change the If statement to this one

if(Integer.parseInt(myNumber.get(i))== Integer.parseInt(myNumber.get((myNumber.size()-1)-i)))

Thats because you were comparing string instead of the actual numbers.

0

You can use the reverse method in the StringBuilder to accomplish this.

public static boolean isPalindrome(String str) {
    return str.equals(new StringBuilder(str).reverse().toString());
}
Sireesh Yarlagadda
  • 12,978
  • 3
  • 74
  • 76