I want to check if the user input is a palindrome or not. But this is not working as expected. Please help.
The code I tried:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String A=sc.next();
for (int i=0; i<A.length()/2; i++){
if(A.charAt(i)==A.charAt(A.length()-i-1)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
}
You're printing "Yes" for every character that has the same character at the opposite end of the String and "No" if not. Modify your loop to return a boolean that tells whether the String is a palindrome or not and then print it at the end like so:
boolean isPalindrome = true;
for (int i=0; i<A.length()/2; i++){
if(!A.charAt(i)==A.charAt(A.length()-i-1)){
isPalindrome = false;
}
}
if(isPalindome){
System.out.println("Yes");
} else {
System.out.println("No");
}