This site requires JavaScript, please enable it in your browser!
Greenfoot back
JasonZhu
JasonZhu wrote ...

2014/3/6

Hep with String Boolean method

JasonZhu JasonZhu

2014/3/6

#
public class Palindrome
{
    public boolean palindrome(String arg)
    {
        String palin = new String();
        for(int i=arg.length();i>0;i--){
            palin+=arg.indexOf(i);
        }
        if(palin.equals(arg)){
            return true;
        }else{
            return false;
        }
    }
}
I am writing a Boolean method that returns true if my input is a palindrome and false if it isn't. However, it only returns false even though my input is "racecar", which is a palindrome. Can someone tell me why this is not working the way I want? Help greatly appreciated!
erdelf erdelf

2014/3/6

#
replace lines 5-8 with
String palin = new StringBuffer(arg).reverse().toString();
davmac davmac

2014/3/6

#
What erdelf suggested should work, I think, but to actually explain the problem with your code:
            palin+=arg.indexOf(i);  
This is wrong; you're asking for the index of a character and the character is the numerical value of i, rather than the character at the position specified by i. I think what you should have write for that line was:
            palin+=arg.charAt(i - 1);  
JasonZhu JasonZhu

2014/3/6

#
Oh I see my mistake, Thanks guys! And sorry for my late reply, I was away from the computer for a couple hours or so.
You need to login to post a reply.