Difference between revisions of "Palindromes"
(EDIT: broke up some paragraphs for ease of reading and added bullets to question) |
m (Fixed photo) |
||
Line 33: | Line 33: | ||
|SideSection= | |SideSection= | ||
− | [[Image:Wiki_trays01.jpg|center]] | + | [[Image:Wiki_trays01.jpg|center]]<BR> |
− | <BR> | + | |
|SolutionCode= | |SolutionCode= |
Revision as of 14:24, 9 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 store the reversed words. You will need to initialize the strings, which means make the strings empty. String reverse1 = "" String reverse2 = "" Then, you will need a for loop to reverse the first word. This loop will start from 0 and finish looping when i >= testWord1.length. The increment will be 1 since we are getting each character from the string. for(int i = 0; i < testWord1.length(); i++) { } Once you have the for loop set up, you will need to go through each letter of the string using charAt(i) and concatenate the letters in reverse order The peusdo-code below concatenates each letter of the string in reversed order. reverse1 = get the letters of the str by charAt(i) + reverse1 Then, you will need another for loop to reverse testWord2. This time, we will use another approach and make the for loop start from the end. It's strongly recommended to try this way, as it will give you a better understanding of how the for loop works. for(int i = testWord2.length()-1; i >= 0; i--) { } The code above starts from the length of testWord2 - 1, and ends when i becomes less than 0. reverse2 = reverse2 + letters of the str by charAt(i) str = "abcde" Once you have the two words reversed, you will need a condition statement to check if they are palindromes. if testWord == reversedTestWord { Then, print out success } else { print out reservedTestWord } One thing to note: strings cannot be compared using the double equals operator '=='. You will need a special method called: testWord.equals(reversedTestWord).
str.equalsIgnoreCase() See below for the solution code. | ||
Code |