Reputation: 1
I have created a palindorme java program which is getting an error.the error is saying int cannot be converted to boolean.
import java.util.Scanner;
public class palindrome
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int l,i;
String s,s1;
System.out.println("Enter your string");
s = sc.nextLine();
l = s.length();
for(i=0;l-i-1;i++)
{
s1 = s + s.charAt(i);
}
if(s1==s)
System.out.println("This is Palindrome");
else
System.out.println("This is not a Palindrome");
}
}
Upvotes: 0
Views: 226
Reputation: 4667
There are quite a few things off here, first here is the fixed code:
public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
int l,i;
String s = "",s1 = "";
System.out.println("Enter your string");
s = sc.nextLine();
l = s.length();
for(i = l - 1; i >= 0; i--)
{
s1 = s1 + s.charAt(i);
}
if(s1.equals(s))
System.out.println("This is Palindrome");
else
System.out.println("This is not a Palindrome");
}
The first thing to fix was your for
loop, as you saw you were getting an error. This was fixed by setting the initial i
to the length minus 1, changing the loop condition to i >= 0
, and using i--
to subtract 1 from i
each loop.
These changes to the loop were made so that the character starting from the last position in the String
is the first one being return by s.charAt(i)
so you can reverse the String
. I think you were attempting to do something along these lines to add the characters starting from the end to a String
.
I also changed s1 = s + s.charAt(i)
to s1 = s1 + s.charAt()
so the correct String
is being appended. (This should probably be StringBuilder
however).
s
and s1
now have the initial condition of ""
instead of nothing.
And finally you cannot compare String
equality with ==
, it must be s1.equals(s)
.
Test Run:
Enter your string
racecar
This is Palindrome
Upvotes: 0
Reputation: 11163
Along with the answer above you can try a different approach. You don't need to go all the string length to check a palindrome. A palindrome can be checked iterating half of the array length like this -
public void checkPalindrome(String strToCheck){
char[] arr = strToCheck.toCharArray();
int size = arr.length;
char [] original = Arrays.copyOf(arr,arr.length);
for (int i = 0; i < size / 2; i++) {
char temp = arr[i];
arr[i] = arr[size-i-1];
arr[size-i-1] = temp;
}
if(Arrays.equals(arr, original)) {
System.out.println("Palindrome");
} else {
System.out.println("Not a palindrome");
}
}
What are done here:
Arrays.equals()
method.Upvotes: 0
Reputation: 1163
For loop condition seems wrong.
for(initial counter; condition to terminate; increase counter) {}
for(i=0; i<l; i++) {}
Upvotes: 1