can you help me i'm not getting output for my palindrome program in Java?

by Love Heals   Last Updated May 23, 2020 00:26 AM

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");
        }


    }
}

Can anyone please help me i'm not getting the required output for my code. I'm a beginner in java...



Answers 3


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--)
Zebediah Perkins
Zebediah Perkins
May 22, 2020 17:12 PM

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
tim-we
May 22, 2020 17:14 PM

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
Bradley
May 22, 2020 17:33 PM

Related Questions



Palindrome Checker Code Stuck in Infinite Loop

Updated January 16, 2019 05:26 AM


How to compare Palindromes

Updated April 23, 2017 15:26 PM