Search code examples
javavalidationequalitypalindrome

Why does this always result in try?


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);
        }       
    }
}

Solution

  • 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){