Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Palindrome problem

  • 02-08-2006 11:48AM
    #1
    Registered Users, Registered Users 2 Posts: 357 ✭✭


    double post sorry


Comments

  • Registered Users, Registered Users 2 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, Registered Users 2 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, Registered Users 2 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