I've written code for my CS class to identify if a user inputted string is a palindrome or not. I've gotten the code to work. However, whenever I execute the code I get this message:
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.charAt(String.java:658)
at palindrome.Palindrome.main(Palindrome.java:14)"
I think there's something wrong with my length
and i
but I'm not sure what. My code is below. I used aabbaa
for the user inputted string.
package palindrome;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
System.out.println ("Enter A String:");
Scanner input = new Scanner (System.in);
String s = input.nextLine();
int length = s.length();
int i = 0;
while (length>= 0) {
if (s.charAt(i) == s.charAt(length-1)) {
i++;
length--;
if (length == i) {
System.out.println ("Your string is a palindrome");
length = 0;
}
}
else {
System.out.println ("Your string is not a palindrome");
length = 0;
}
}
}
}