String index out of bounds error 5???
hey, im working on a program that tests to see if a string is a palindrome or not. It has to remove all characters and spaces.
Heres the program:
Code Java:
import java.util.*;
public class PalindromeTester
{
public static void main(String[]args)
{
String str,another="y";
int left,right;
Scanner scan=new Scanner(System.in);
while(another.equalsIgnoreCase("y"))
{
System.out.println("enter a potential palindrome: ");
str=scan.nextLine();
str=str.replaceAll("!"," ");
str=str.replaceAll("."," ");
right=str.length();
left=0;
while(str.charAt(left)== str.charAt(right) && left < right)
{
left++;
right--;
}
System.out.println();
if(left<right)
System.out.println("That string is NOT a palindrome. ");
else
System.out.println("That string IS a palindrome");
System.out.println();
System.out.println("Test another palindrome?(y/n)");
another=scan.nextLine();
}
}
}
It compiles fine, but when i run the program i get this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:686)
at PalindromeTester.main(PalindromeTester.java:26)
What does this mean? and one other question. If i use the string.replaceAll() method, can i replace it with nothing by doing this string.replaceAll("(puntuationmarkshere),"");
Re: String index out of bounds error 5???
It means your Array is only 5 items long, and you are attempting to access Index 5. Since Indexes start at 0, your index range is: 0-4.
Re: String index out of bounds error 5???
thank you! i just fixed it :) im starting to understand these error messages better and better. now what about the second question?
Re: String index out of bounds error 5???
Yes you can replace the string with ""