I’m not really sure why I am getting this error. The code is meant to test palindromes disregarding punctuation.
So here is my code:
char junk;
String temp = "";
for (int i = 0; i < txt.length(); i++)
{
junk = txt.charAt(i);
if (Character.isLetterOrDigit(txt.charAt(jumk)))
{
temp += junk;
}
}
txt = temp;
left = 0;
right = txt.length() -1;
while (txt.charAt(left) == txt.charAt(right) && right > left)
{
left++;
right--;
}
java.lang.StringIndexOutOfBoundException : String index out of range 0
at PalindromeTester.main(PalindromeTester.java:35)
and line 35 is as following:
while (txt.charAt(left) == txt.charAt(right) && right > left)
The variable
yPis your character at indexi, not an index (as you are using it on the line giving you the error). Change that line to:EDIT FOR THE NEW PROBLEM:
You don’t need a while loop to check if the user entered nothing, since you don’t want to do something repeatedly in this case (which is what loops are for). Since you only want to do something once, i.e. print out how many palindromes they have found, you can just use an
ifstatement. The structure would look like this:EDIT 2:
Try changing
to
Since if left==right, that means they are both on the median character in an odd-length string (e.g. the ‘y’ in kayak) which means the string is a palindrome.