0

The program checks if the reverse of string and original string are same and for getting reverse of string,i am using stringbuilder in java and to compare the revese,eual of java but output is not correct.If original string and reverse string are same,output yes else output NO .

import java.io.*;
import java.util.Scanner;
import java.lang.*;
public class Stringuse {
    private static Scanner in;
    public static void main(String[] args) {
        in = new Scanner(System.in);
        String s=in.next();
        StringBuilder sb=new StringBuilder(s);
        sb.reverse().toString();
        System.out.println(sb);
        boolean ans=sb.equals(s);
        System.out.println(ans);
        if(ans==true)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
kolaveri
  • 59
  • 1
  • 2
  • 15

2 Answers2

4

You probably just need to change it to

boolean ans = sb.toString().equals(s);

since only Strings equal other Strings; a StringBuilder cannot be equal to a String.

...though you can also write sb.reverse() instead of sb.reverse().toString(), and if (ans) instead of if (ans == true).

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • StringBuilder cannot be equal to String, and also to other StringBuilder with same content, because StringBuilder doesnt implement equals method – Rustam Mar 18 '16 at 21:44
1

I just made few changes as suggested in comments and it works fine now.

public static void main(String[] args) {
  in = new Scanner(System.in);
  String s=in.next();
  StringBuilder sb=new StringBuilder(s);
  boolean ans= sb.reverse().toString().equals(s);
  if(ans==true)
    System.out.println("Yes");
  else
    System.out.println("No");
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
kolaveri
  • 59
  • 1
  • 2
  • 15