Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Palindrome problem

Options
  • 02-08-2006 11:48am
    #1
    Registered Users Posts: 357 ✭✭


    double post sorry


Comments

  • Registered Users Posts: 357 ✭✭apoch632


    import java.util.*;
    import javax.swing.*;
    import java.awt.*;

    public class reverseString()
    {
    public String wordEntered;
    public String wordReversed;

    public static void main(String[] args)
    {
    JOptionPane.showMessageDialog(null,"Hello and welcome to Palindrome Checker");
    wordEntered = JOptionPane.showInputDialog("Please enter the string you wish to reverse and check");
    palindromeChecker(wordEntered);
    System.exit(0);
    }

    public static String palindromeChecker(String n)
    {
    String entered = n

    if(entered.length() == 0)
    {
    JOptionPane.showMessageDialog("You have entered a blank string and program will now exit");
    return null;
    }
    String flippedWord = flipWord(entered);
    if(flippedWord == entered)
    {
    JOptionPane.showMessageDialog(null,"The word entered is " + entered + " The reverse is " + flippedWord + " it is a Palindrome");
    return flippedWord;
    }
    else if(flippedWord!= entered)
    {
    JOptionPane.showMessageDialog(null,"The word entered is " + entered + " The reverse is " + flippedWord + " it is a Palindrome");
    return flippedWord;
    }
    else
    {
    return null;
    }
    }
    public static String flipWord(String y)
    {
    String x = "";
    for(int i = y.length()-1;i>=0;i--)
    {
    x += y.charAt(i);
    }
    return x;
    }

    No matter what string i enter and then reverse e.g. navan it is saying it is not a palindrome. Anyone have any ideas how to fix this.


  • Registered Users Posts: 1,636 ✭✭✭henbane


    I haven't gone through the whole program but
    flippedWord == entered
    
    should be
    flippedWord.equals(entered)
    
    for String comparison.


  • Registered Users Posts: 357 ✭✭apoch632


    Forgot about that. Just slipped my mind. Thanks


  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    for(int i = 0; i < enteredWord.Length/2; i++)
        if(enteredWord[i] != enteredWord[enteredWord.Length - 1 - i])
             return false;  // not a palindrome.
    
    That'd be better than duplicating the word by reversing it, then doing a comparison :p


Advertisement