Difference between revisions of "Palindromes"
(Fixed typos, formatting, etc in problem description.) |
|||
Line 4: | Line 4: | ||
|Problem= | |Problem= | ||
− | This question will help you practice with | + | This question will help you practice with string methods and <b>for</b> loops.<br> |
− | <br | + | <br> |
− | Complete the program | + | Complete the program titled Palindrome that checks if a word is a palindrome. |
− | If the word is palindrome, print out "It's a palindrome." using System.out.println(). | + | If the word is palindrome, print out "It's a palindrome." using System.out.println(). |
− | Otherwise, print out reversed order of the word.<br | + | Otherwise, print out the reversed order of the word.<br> |
− | <br | + | <br> |
− | For example, "deed" and "civic" are palindromes.<br | + | For example, "deed" and "civic" are palindromes.<br> |
− | "tomato" and "mama" are not palindromes.<br | + | "tomato" and "mama" are not palindromes.<br> |
− | <br | + | <br> |
− | + | Find out whether the two strings provided are palindromes or not. | |
The program that you need to complete is provided below. | The program that you need to complete is provided below. | ||
− | <br | + | <br> |
<pre> | <pre> | ||
public class Palindrome | public class Palindrome |
Revision as of 19:27, 8 April 2010
Back to the Program-A-Day homepage
ProblemThis question will help you practice with string methods and for loops. public class Palindrome { public static void main(String[] args) { String testWord1 = "Arewenotdrawnonward,wefew,drawnonwardtonewera" String testWord2 = "Murderforajarofredrum" // Your code goes here } } |
Palindromes
| |
---|---|---|
SolutionFirst of all, you will need to declare two string objects to get reversed words. String reverse1 = "" String reverse2 = ""
for(int i = 0; i < testWord1.length(); i++) { }
reverse1 = get the letters of the str by charAt(i) + reverse1
for(int i = testWord2.length()-1; i >= 0; i--) { }
reverse2 = reverse2 + letters of the str by charAt(i) str = "abcde" if testWord == reversedTestWord { Then, print out success } else { print out reservedTestWord }
testWord.equals(reversedTestWord).
str.equalsIgnoreCase()
| ||
Code |