0

I am trying to create a palindrome for my string but my equals method() is not working. The program is producing reverse value of the given string but equals method is not working.

import java.io.*;

class Palindrome {

    public static void main(String [] args) throws IOException {
        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
        String s = br.readLine();
        int length = s.length();
        String rev = " ";
        for(int i = length-1; i>=0; i--)
            rev=rev+s.charAt(i);
        String str = rev;
        if(s.equals(str)
            System.out.print("Palindrome");
        else
        {
            System.out.print("Not Palindrome");
            System.out.print(rev);
        }
    }
}
ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • Hello, you could also use `reverse` method of `StringBuilder` to reverse the input and then then check if they are equal with the reversed `String` you obtain from the `StringBuilder.` – Bleach Nov 24 '18 at 19:52

1 Answers1

0

Your problem is that you should initialize string with empty string: String rev = "". Moreover you have some following issues to fix:

  1. You have to close the stream
  2. It is much better to use StringBuilder instead of String concatenation.

P.S.

What about refactor you code? I think it is better to use Scanner and not using string concatenation or StringBuilder, just compare character by character:

public static void main(String... args) throws IOException {
    try (Scanner scan = new Scanner(System.in)) {
        System.out.println(isPalindrome(scan.nextLine()) ? "Palindrome" : "Not Palindrome");
    }
}

public static boolean isPalindrome(String str) {
    for (int i = 0, j = str.length() - 1; i < j; i++, j--)
        if (str.charAt(i) != str.charAt(j))
            return false;
    return true;
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35