-4

Im writing this java code for school. I need to see if the data is a palindrome or not and then let the user know the results. My eyes are bleeding. I can't figure this out!

import javax.swing.JOptionPane;
import helpers.*;

public class Palindrome {
    public static boolean check(String dataInput) { 
        boolean test = false;
        String reverseDataInput = new StringBuffer(dataInput).reverse().toString();
        if (dataInput == reverseDataInput){
            test=true;
            return test;
        }
        return test;
    }

    public static void main(String[] args) {

        String inputString = "";
        int number = 0;
        boolean isPalindrome = false;       

        number = helpers.InputUtilities.getIntegerInput(inputString, -99999, 99999);

        String str = Integer.toString(number);
        isPalindrome = check(str);
        if (isPalindrome = true){
            JOptionPane.showMessageDialog(null, str + " is a palindrome!", "Area", JOptionPane.PLAIN_MESSAGE);
        }
        else {
            JOptionPane.showMessageDialog(null, str + " is not a palindrome!", "Area", JOptionPane.PLAIN_MESSAGE);
        }       
    }
}
Zach
  • 4,652
  • 18
  • 22

2 Answers2

0

First java Strings are compared with .equals() not == because they are objects (see this).

if (dataInput.equals(reverseDataInput))

Second your if statement is a bit wrong.

if (isPalindrome = true){

Instead

if (isPalindrome == true){

or (this looks better to some people)

if (isPalindrome){
Community
  • 1
  • 1
BitNinja
  • 1,477
  • 1
  • 19
  • 25
  • Thanks guys. Sorry it was so simple. I wouldn't have thought to check for the == so although it was posted before, I feel like I needed help. Thank you so much! – helloWorldIsAlliKnow Jul 20 '14 at 20:24
0

I've seen this question before (here: Local variable not used).

The problem is simply the if: statement. Replace

if (isPalindrome = true)

with

if (isPalindrome)

You also need to modify your first if:

if (dataInput == reverseDataInput)

by

if (dataInput.equals(reverseDataInput))

Because == checks for pointer equality and since you generate a new string, the two strings are not the same, they are equal, but not the same...

Community
  • 1
  • 1
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555