Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Beginner Program Help (if, else issue)

I'm practicing making my own String reversal tool. to top the learning process of I used the method in a simple application. BUT..
When I run my code in Eclipse, Even if word is = racecar and reversed becomes = racecar (word reversed). the else is displayed.. Telling me that word and reverse are never equal.. but..ion that case they are? Right? Please give me some advice, this is quite the bummer. Thank you.

import java.util.Scanner;

public class Main {

    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args){

    System.out.println("Please enter a word, I'll show it reversed ");
    System.out.println("and tell you if it is read the same forward and backward(A Palindrome)!: ");
        String word = sc.nextLine();
        String reverse = reverse(word);

        if (reverse == word){
            System.out.println("Your word: " + word + " backwards is " + reverse + ".");
            System.out.println("Your word is read the same forward and backward!");
            System.out.println("Its a Palindrome!");
        }

        else {
            System.out.println("Your word: " + word + " backwards is " + reverse + ".");
            System.out.println("Your word is not read the same forward and backward!");
            System.out.println("Its not a Palindrome!");
        }



    }

    public static String reverse(String source){

        if (source == null || source.isEmpty()){
            return source;
        }

        String reverse = "";

        for(int i = source.length() -1; i >= 0; i--){
            reverse = reverse + source.charAt(i);
        }

        return reverse;
    }

}
like image 555
Andrew Fabian Avatar asked Feb 26 '26 07:02

Andrew Fabian


1 Answers

Always use String#equals to compare Strings. == will compare if the references are equal which doesn't really work for comparing equal strings due to how they are stored.

if (reverse.equals(word))
like image 95
Mark M Avatar answered Mar 02 '26 06:03

Mark M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!