user2207839
user2207839

Reputation: 77

Verify the palindrome in Java. Can you help me to find what's the issue with this code

Can you help me to find the bug in this code. When I test this with a string that is not a palindrome, I get the message that it is a palindrome.

import java.util.*;

public class Main{


    public static void main(String args[]){
        String input = "";
        System.out.println("Enter the string to verify palindrome");
        Scanner scan = new Scanner(System.in);
        input = scan.nextLine();

        Main m = new Main();
        if(m.palindrome(input))
        System.out.println(" The string " + input + " is a palindrome ");
        else System.out.println(" The string " + input + " is not a palindrome ");
    }

    private boolean palindrome(String input){
        String reverse = input;
        int j;
        for(int i=0;i<=reverse.length()-1;i++){
            for( j=reverse.length()-1;j>=0;){
                if(reverse.charAt(i)== reverse.charAt(j)){
                    return true;
                }
                else{
                    return false;
                }   

            }j--;

        }
        return false;   
    }

}

Upvotes: 1

Views: 740

Answers (1)

Aurand
Aurand

Reputation: 5537

if(reverse.charAt(i)== reverse.charAt(j)){
   return true;
}

You are returning true if the first and the last character are the same without going on to check any other character.

I'd say the better approach is to continue stepping through the word until you find a character that does not match or until you finish. If you find a character that does not match, return false. If you finish, return true.

Upvotes: 2

Related Questions