Results 1 to 12 of 12
  1. #1
    arson09 is offline Member
    Join Date
    Mar 2010
    Posts
    21
    Rep Power
    0

    Default Test for Palindrome

    I'm a little unsure on how to set it up to the point where words like "Radar" is still considered to be a Palindrome... Right now, "Radar" is only considered a Palindrome if it's entered as "radar." Also a word like "Radar's radar" where all white-space characters and punctuation marks are ignored.. I believe i have to use the IgnoreCase method, but i'm still ignorant on how to use it..


    Java Code:
    import java.util.*;
    import java.io.*;
    
    public class Palindrome test
    {
       public static void main(String[] args)
       throws java.io.IOException
       {
     // variables
       int i;
    
    // Create Scanner
                                                     
       Scanner sc = new Scanner(System.in);
    
    //Prompt user to enter a string
    
       System.out.print("Please enter palindrome: ");
       String s = sc.nextLine();
       
    // Show result of string entered
       if(isPalindrome(s)) {
     
       System.out.println(s + " is a palindrome");
       }
        
       else {
       System.out.println(s+ " is not a palindrome");
    
      }
    }                                                
       
    // Check if a string is a plaindrome
    
    public static boolean isPalindrome(String s) {
       
    // The index of the first character in the string
       int low = 0;
    
    // The index of the last character in the string
       int high = s.length() -1;
       
      while (low<high) {
      if(s.charAt(low) != s.charAt(high) )
       return true; // Not a palindrome
       
    low ++;
    high--;
    }                                                
       
    return true; // the string is a palindrome
    
     }
       
    }
    Last edited by arson09; 04-28-2010 at 08:30 PM.

  2. #2
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    6

    Default

    Look at the toLowerCase(), toUpperCase(), and equalsIgnoresCase() methods within the String class. Those should be just what you want, just depends how you want to go about it.
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  3. #3
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    A few suggestions, you'd want a method named isPalindrome() to return true, if the string entered is a palindrome, not the other way around. Next, how do you check if the word is a palidrome? The basic step would be to compare the first and last letter, if they match, compare the second and second to last letter. Hence, recursion. The exit condition would be if you get a single letter string, or an empty string, in this case return true. About comparing letters without case getting in the way, the Character class has a static method toUpperCase(char c), (and toLowerCase(char c)), so you can compare the letters this way:
    Java Code:
    if(Character.toUpperCase(someString.charAt(0)) == Character.toUpperCase(someString.charAt(someString.length()-1)))
     doSomething();
    Since the charAt() method returns a char, you can't use equalsIgnoreCase() directly.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    As in your to toUpperCase question in the sun fora, I like to use pseudo-code to figure things out. For your isPalindrome method, one way to do it like so:

    Java Code:
    method isPalindrome: input String, inputString, returns true if palindrome, else false
      Change string to all upper case // use String#toUpperCase(String s) method for this
      create String nonWhiteSpaceString = "".
      for each char in inputString,
        if the char is not white-space, add it to the nonWhiteSpaceString: nonWhiteSpaceString += String.valueOf(the char)
      end for
      set boolean isPalindrome to true // assume it's a palindrome to begin with
      create int variables leftIndex and rightIndex and set equal to 0 and nonWhiteSpaceString.length -1 respectively
      for i goes from 0 to nonWhiteSpaceString.length / 2 do
        get leftChar and rightChar using the indices.  
        If not equal 
          return false // no need to keep checking if not a pallindrome
        end if
        increment leftCharIndex
        decrement rightCharIndex
      end for
      return true
    end method
    Again as in the previous question, Character's isWhiteSpace method will come in handy.

  5. #5
    arson09 is offline Member
    Join Date
    Mar 2010
    Posts
    21
    Rep Power
    0

    Default

    This is what i have so far..

    Am i on the right track???


    Java Code:
    import java.util.*;
    import java.io.*;
    
    public class Palindrome
    {
       public static void main(String[] args)
       throws java.io.IOException
       {
     // variables
       int choice;
    
    // Create Scanner
    
       Scanner sc = new Scanner(System.in);
    
    do{
       System.out.print("Press 1 to test Palindrome or Press 2 to exit: ");
        choice = sc.nextInt();
        sc.nextLine();
    
        if(choice == 1) {
    //Prompt user to enter a string
    
       System.out.print("Please enter string: ");
       String str = sc.nextLine();
    
    // Test if palindrome
    
       if(isPalindrome(s))         
    
       System.out.println(str + " is a palindrome");
    
    
       else
       System.out.println(str+ " is not a palindrome");
    
      }
          } while(choice == 1);
    
    }
       
    
    
    
    // Check if a string is a plaindrome
    
    public static boolean isPalindrome(String s) {
    
    // The index of the first character in the string
       int low = 0;
       
    // The index of the last character in the string
       int high = s.length() -1;
    
    // Word backwards
       int backwards = high;
     
       
      while (low<high) {
      if(s.charAt(low) != s.charAt(backwards) )
       return false; // Not a palindrome
    
    low ++;
    backwards--;
    }
    
    return true; // the string is a palindrome
       
     }
    private static String removeSpaces(String s){
         String r= "";
          for (int i =0; i< s.length(); i++)
             if(s.charAt(i) != ' ')
                   r=r+s.charAt(i);
    
         return r;
      }
    }
    Last edited by arson09; 04-28-2010 at 09:16 PM.

  6. #6
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    I'd still advise you to try and solve this problem recursively. I'm not saying your solution isn't valid, it's just good practice to try and look at a problem from a different viewport. I'll even start you off:
    Java Code:
    public static boolean isPalindrome(String s) {
      if(s.length() <= 1) return true; //base case
      if(s.charAt(0) == s.charAt(s.length()-1)) //add in case insensitivity
        //what to do here?
      return false;
    }
    Just fill in one line and slightly modify the equality checking, and you have your solution. Again, I'm proposing this as exercise, I'm not saying this is the one and only way this problem should be solved.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  7. #7
    arson09 is offline Member
    Join Date
    Mar 2010
    Posts
    21
    Rep Power
    0

    Default

    Thank you guys for the help. I went about it in a little easier route IMO.



    Java Code:
    import java.util.*;
    import java.io.*;
    
    public class Palindrome
    {
       public static void main(String[] args)
       throws java.io.IOException
       {
    
     Scanner sc = new Scanner(System.in);
      //Prompt user to enter a string
    
       System.out.print("Please enter string: ");
       String str = sc.nextLine();
       String str_wo_space = "";
       char cur_char;
       int i;
    
     for(i=0;i<str.length(); i++)
     {
     cur_char = str.charAt(i);
    
       if(Character.isLetterOrDigit(cur_char))
    
            str_wo_space += cur_char;
     }
       
    String reverse = "";
      for(i=str_wo_space.length()-1; i>=0; i--)
          reverse += str_wo_space.charAt(i);
     
            if(str_wo_space.compareToIgnoreCase(reverse) == 0)
    
                   System.out.println(str+ " Is a palindrome");
       
              else
       
                  System.out.println(str+ " Is not a palindrome");
       }
    }

  8. #8
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Java Code:
    "abc".compareToIgnoreCase("ABC") == 0;
    An easier way to write this is:
    Java Code:
    "abc".equalsIgnoreCase("ABC");
    While the method you've written works, in my opinion is a step back. Try this on for size:
    Java Code:
    boolean isPalindrome(String s) {
      if(s.length() <= 1) return true; //base case
      if(Character.toUpperCase(s.charAt(0)) == Character.toUpperCase(s.charAt(s.length()-1)))
        return isPalindrome(s.substring(1,s.length()-1)); //recursive call
      return false; //if the first and last characters are not equal, return false
        
    }
    So basically, what this does is reducing the problem to down to smaller problems. The advantage of this, is it doesn't have to reverse the whole string to find out if it's not a palindrome, it bails out as soon as it finds a counter case. You could add in ommission of white spaces, and that would be it.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  9. #9
    Henkkie055 is offline Member
    Join Date
    Sep 2010
    Posts
    1
    Rep Power
    0

    Unhappy How to make the right flowchart for a palindrome

    Dear people who want to help:),
    I have to make two flow charts for a program that determines if a word a palindrome is or not. So I need in text written algorithm for this program.
    Seems to be an easy job for most people. But i'm having a hard time construction the second one.

    The first one is like this:

    1.Ensure all values are proper
    2. Read through string from left to right
    3. Reverse string
    4. If both are identical, you've got your palindrome

    Ofcourse I have more specific points in my flow chart.

    Now to get a total different one about the same problem is it a parlindrome or not?
    What you can change is the third step. My idea was, to read the first letter and the last letter and check if the match. If so carry on with the second letter. But how does he now when to stop. What i'm trying to do is to reach the middel, but how does he know when he's in the middel. I saw a few examples of the codes with wich you can make the actual program and i noticed that the divided the amount of letters by 2. Why's that. What's next after you divided?
    I hope someone can help me.

    Thanks in advance!

  10. #10
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,435
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Henkkie055 View Post
    Now to get a total different one about the same problem is it a parlindrome or not?
    What you can change is the third step. My idea was, to read the first letter and the last letter and check if the match. If so carry on with the second letter. But how does he now when to stop. What i'm trying to do is to reach the middel, but how does he know when he's in the middel. I saw a few examples of the codes with wich you can make the actual program and i noticed that the divided the amount of letters by 2. Why's that. What's next after you divided?
    If you have 'direct access' to all characters in your string you can access character #0, #1, #2, ... #n-1. If the characters at position i and n-1-i all match you have a palindrome. If you have to match characters i and j= n-1-i you can check if i < j (because otherwise you're rematching the same characters for a second time).

    kind regards,

    Jos

  11. #11
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    Quote Originally Posted by Henkkie055 View Post
    Dear people who want to help:),
    I have to make two flow charts for a program that determines if a word a palindrome is or not. So I need in text written algorithm for this program.
    Seems to be an easy job for most people. But i'm having a hard time construction the second one.

    The first one is like this:

    1.Ensure all values are proper
    2. Read through string from left to right
    3. Reverse string
    4. If both are identical, you've got your palindrome

    Ofcourse I have more specific points in my flow chart.

    Now to get a total different one about the same problem is it a parlindrome or not?
    What you can change is the third step. My idea was, to read the first letter and the last letter and check if the match. If so carry on with the second letter. But how does he now when to stop. What i'm trying to do is to reach the middel, but how does he know when he's in the middel. I saw a few examples of the codes with wich you can make the actual program and i noticed that the divided the amount of letters by 2. Why's that. What's next after you divided?
    I hope someone can help me.

    Thanks in advance!
    This thread is also five months old. If you have further questions after reading JosAH's reply, please start a new thread.

  12. #12
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,435
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Zack View Post
    This thread is also five months old. If you have further questions after reading JosAH's reply, please start a new thread.
    Darn, I didn't pay attention to the posting dates, silly me ... ;-)

    kind regards,

    Jos

Similar Threads

  1. StringTokenizer in a Palindrome program
    By jeremyk in forum New To Java
    Replies: 10
    Last Post: 02-13-2010, 06:35 PM
  2. HELP...Palindrome
    By d7o0om in forum New To Java
    Replies: 12
    Last Post: 11-13-2009, 03:32 AM
  3. palindrome problem
    By Blaedel in forum New To Java
    Replies: 5
    Last Post: 10-03-2009, 12:52 AM
  4. Palindrome problem
    By Mika in forum New To Java
    Replies: 4
    Last Post: 02-18-2009, 02:46 PM
  5. Palindrome Test
    By Ada in forum New To Java
    Replies: 1
    Last Post: 05-26-2007, 01:36 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •