Here's my Java code to find a palindrome of a string. It shows o/p as "Palindrome" even though the i/p that I've entered is not. Can anyone please help.
String a = sc.next();
char b[] = a.toCharArray();
char d[] = b;
int size = a.length();
int beg=0,end=size-1;
while(beg<=end)
{
char temp = b[beg];
b[beg] = b[end];
b[end] = temp;
beg++;
end--;
}
if(d.equals(b))
{
System.out.print("Palindrome");
}
else
System.out.print("Not a Palindrome");
There are a few problems with your implementation. First of all -
while(beg<=end)
{
char temp = b[beg];
b[beg] = b[end];
b[end] = temp;
beg++;
end--;
}
Debug carefully and see do you really have d[] as the reverse of b[] at the end of this while loop
Secondly,
if(d.equals(b))
{
System.out.print("Palindrome");
}
This is not the correct way to compare if all the array elements are same in both of the array. If you look into the implementation or try out with some sample array you will be able to see it yourself.
To check palindrome, very simple approach is to reverse the string using StringBuilder
and check if it's equal to the original string -
Scanner sc = new Scanner(System.in);
String a = sc.next();
String aRev = new StringBuilder(a).reverse().toString();
if (a.equals(aRev)) {
System.out.print("Palindrome");
} else {
System.out.print("Not a Palindrome");
}
Another better approach is to run a loop from beginning to middle of the string and keep an index from end to middle. Then check both forward index and backward index.
Scanner sc = new Scanner(System.in);
String a = sc.next();
boolean palindrome = true;
for (int i = 0; i < a.length() / 2; i++) {
if (a.charAt(i) != a.charAt(a.length() - i - 1)) {
palindrome = false;
break;
}
}
System.out.println(palindrome ? "Palindrome" : "Not Palindrome");