-2

Below is a program for palindrome. If it is palindrome it will print YES else NO. I am unable to understand what's the difference in calling:

> int n=Integer.parseInt(in.nextLine()); 

> or int n=in.nextInt();

because both is doing the same work. 1st one is taking Stringas input then converting it into int 2nd one is taking directly int.

when the 1st one is taken there is no error. But when 2nd one is taken it gets stored in n then it prints YES.(when debugged i found out that it gets stored in n but it skips the input string str and then it compares with str and s and prints YES).

So can anyone explain the logic behind this.

public class Test1 {
public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    //int n=Integer.parseInt(in.nextLine());
   int n=in.nextInt();
    while(n!=0){
    String s="";
    String str=in.nextLine();
    for(int i=str.length()-1;i>=0;i--){
        s=s+str.charAt(i);
    }
    if(str.equals(s) ){
        System.out.println("YES");
    }
    else{
        System.out.println("NO");
    }
    n--;
    }
  }    
}
Jérôme
  • 1,133
  • 2
  • 16
  • 21
Fawkes
  • 105
  • 1
  • 9

1 Answers1

0

I guess that with Scanner you expect the String to be verified... in that case this line int n=in.nextInt(); will throw a java.util.InputMismatchException exception if the input is not a number.

The verification would be easier to achieve by using StringBuilder, like this:

Scanner in=new Scanner(System.in);
String original = in.nextLine();
StringBuilder reversa = new StringBuilder(original).reverse();
if (reversa.toString().equals(original)) {
    System.out.println("YES");;
} else {
    System.out.println("NO");;
}
Dazak
  • 941
  • 2
  • 8
  • 17