Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error on using uppercase in palindrome prog in java

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)
like image 664
Satyam Pandey Avatar asked Jan 24 '26 15:01

Satyam Pandey


2 Answers

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) {
like image 83
Mureinik Avatar answered Jan 26 '26 13:01

Mureinik


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();
like image 44
AntoineB Avatar answered Jan 26 '26 13:01

AntoineB