package Assignments;
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
int i=0,j=str.length()-1,count=0;
while(i!=j) {
if(str.charAt(i)!=str.charAt(j)) {
count++;
break;
}
i++;
j--;
}
if(count!=0) {
System.out.println("Not a Palindrome");
}
else {
System.out.println("Palindrome");
}
}
}
Upon entering Uppercase letter in input it is showing error. "assa" as input is working fine but "Assa" is showing error. I know it is a minor fault somewhere but I am new to java. Can anyone help?
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:709)
at Assignments.Assignment1.main(Assignment1.java:12)
a and A are not the same character. If you don't care about the case, you could convert all the character to lowercase (or to upper case) explicitly when comparing them:
while (i != j) {
if (Character.toLowerCase(str.charAt(i)) != Character.toLowerCase(str.charAt(j))) {
count++;
break;
}
i++;
j--;
}
EDIT:
The updated exception in the question clarifies the problem - it is unrelated to upper/lower case discrepancies, but to a wrong handling of strings with an even number of characters. To handle this you could use the < operator instead of !=:
while (i < j) {
A and a are not the same character, so it is normal that the string doesn't match.
What you could do is, before processing the string to see if it's a palindrome, you convert it to lowercase:
str = str.toLowerCase();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With