Search code examples
javaeclipselocal-variablespalindrome

Local variable not used


I am trying to make a test of whether an inputted word is a palindrome or not (the same spelled forward and backward). From what I can see it should work but Eclipse says "The value of the local variable isPalindrome is not used" , but it is used. The problem is that even if the word is not a palindrome it says it is.

import java.util.Scanner;

public class Palindrome {
    public static void main(String[] args) {
        String phrase;
        char[] phraseLetters;
        int endChar;
        boolean isPalindrome;

        Scanner input = new Scanner(System.in);
        System.out.println("Enter a word or phrase.");
        phrase = input.nextLine();
        input.close();

        phrase = phrase.toLowerCase();
        phrase = phrase.replaceAll(" ","");
        phraseLetters = phrase.toCharArray();

        endChar = phraseLetters.length - 1;

        for (int i = 0; i < phraseLetters.length; i++) {
            if (phraseLetters[i] != phraseLetters[endChar]) {
                isPalindrome = false;   
            } else {
                isPalindrome = true;
                endChar -= 1;
            }
        }

        if (isPalindrome = true) {
            System.out.println("This word or phrase entered is a palindrome.");
        } else {
            System.out.println("This word or phrase is not a palindrome.");
        }
    }
}

EDIT: I have tried the if statement being

    if (isPalindrome == true) 

and

    if (isPalindrome)

In both cases Eclipse says "The local variable isPalindrome may not have been initialized," in this if condition.

FINAL EDIT:

I have since moved on, and rewritten this code, however I just went back and fixed my original code if anyone still looks at this.

I initialized isPalindrome at the beginning of the code:

Boolean isPalinddrome = True;

I changed the for-loop condition to:

for (int i = 0; (i < phraseLetters.length) && (isPalindrome); i++)

Finally I changed if (isPalindrome = true) to if (isPalindrome)


Solution

  • if (isPalindrome = true) should be if (isPalindrome == true) (or if (isPalindrome) better! Actually this error is another good reason why not asking if someBoolean == true which is a bad style)

    By typing if (isPalindrome = true) you're assigning, again, the value true to the variable isPalindrome. And since you're only assigning value to it, the compiler warns you about unused variable.

    It's also good to know this:

    At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.

    So, when you do if (isPalindrome = true) then the if condition is always satisfied.