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

2013/4/30

Plz explain this piece of code!

hkrhässleholm hkrhässleholm

2013/4/30

#
Hi friends! This part of the code is done by one of my teacher and the codes are actually the answer of the following question: "Write a recursive method that checks if a String sent in as parameter is a palindrome (Palindrome = Reads the same from both left and right. I.e. “anna” and “xyzyx”). The method shall return true if the parameter is a palindrome, false otherwise. The method signature shall look like this: public boolean isPalindrome(String s)" But I have no idea how the code is working here , specially the two if statements. Plz anyone explain to me, thanks in advance!
private boolean isPalindrome(String s) {
if (s.length() == 0 || s.length() == 1) { 
return true; 
}
else if (s.charAt(0) == s.charAt(s.length()-1)){ 
return isPalindrome(s.substring(1, s.length()-1)); 
} 
return false; 
}
JetLennit JetLennit

2013/4/30

#
1st off, s.length() checks the length and || is a conditional or, so (s.length() == 0 || s.length() == 1) means if the strings length is 0 or 1 it will return true..... s.charAt() checks what letter is at a certain point, so (s.charAt(0) == s.charAt(s.length()-1)) checks if the first letter and the length minus 1 and sees if they are the same..... Hope this helps!
danpost danpost

2013/4/30

#
To be more specific, 's.length-1' refers to the last letter in the string; so, (s.charAt(0) == s.charAt(s.length()-1)) checks the first letter with the last letter. Line 6 says to return what is returned from calling this method again when using the string with both end letters removed.
hkrhässleholm hkrhässleholm

2013/4/30

#
thanks! But I am still now confused. Can you please tell me how does 's.length-1' refers to the last letter in the string? and at this line "return isPalindrome(s.substring(1, s.length()-1));" why we are using the parameter 1?
Gevater_Tod4711 Gevater_Tod4711

2013/4/30

#
1. The lenght of the string is always the number of characters. But if you use charAt(int) you need to start counting by 0 and not by 1. Therefore the s.length()-1 2. Concerning substring it's the same than charAt. 1 is not the first but the second char of the string. And using substring(1, s.length()-1) you have a substring without the first and the last char of the old string.
You need to login to post a reply.