-1
import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);
        int i;
        String A=sc.next();
        String B= "";
        /* Enter your code here. Print output to STDOUT. */
        for(i=A.length()-1;i<=0;i--){
        B = B+A.charAt(i);
        }

        if(A.equals(B)){
            System.out.println("Yes");
        }
        else{
            System.out.println("No");
        }


    }
}

I'm not getting the required output for my code. I'm a beginner in Java.

halfer
  • 19,824
  • 17
  • 99
  • 186

3 Answers3

1

The reason your program isn't giving you the desired output is because your for-loop is incorrect.

for(i.A.length()-1; i <= 0; i--) {/.../}

You are basically saying, whilst i is less than or equal to zero, execute the loop. i by default is greater than 0.

enter image description here

You can achieve a Palindrome check multiple ways. 2 Examples.

Example 1 using for-loop:

String A = "radar";
String B = "";

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

System.out.println(A.equals(B) ? "Yes" : "No");

Example 2 with StringBuilder.

String A = "radar";
StringBuilder B = new StringBuilder(A).reverse();

System.out.println(A.equals(B) ? "Yes" : "No");
Bradley
  • 327
  • 2
  • 11
0

You are constantly getting an output of "No" because you're checking if i is less than or equal to zero on each loop, while you should be checking for greater than or equal to.

Change for (i = A.length() - 1; i <= 0; i--)

to

for (i = A.length() - 1; i >= 0; i--)
0

The for loop runs as long as the condition holds, in your case i<=0. Unless the input has length 0 this condition never holds, thus the body of the for loop never gets executed and you immediately skip to if(A.equals(B))... which will always be false (except for the input ""). It should be i>=0.

tim-we
  • 1,219
  • 10
  • 16