3
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)
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • `A` is not equals to `a`. *is showing error* i think you ean it shows *Not a Palindrome* – Jens Mar 26 '20 at 11:12

3 Answers3

3

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) {
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Still its showing the same error Assa 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) – Satyam Pandey Mar 26 '20 at 11:17
1

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();
AntoineB
  • 4,535
  • 5
  • 28
  • 61
1

Replace

if(str.charAt(i)!=str.charAt(j)) 

with

if(Character.toUpperCase(str.charAt(i))!=Character.toUpperCase(str.charAt(j))) 

Alternatively,

Replace

if(str.charAt(i)!=str.charAt(j)) 

with

if(Character.toLowerCase(str.charAt(i))!=Character.toLowerCase(str.charAt(j)))

The key is to compare the characters in the same case.

Apart from this, you also need to

replace

while(i!=j)

with

while(i < j)

in order to avoid StringIndexOutOfBoundsException.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110