StringIndexOutOfBounds Exception
Hello people my program is supposed to be a tool designed to find palindromes. For those that do not know what a palindrome is... it is basically a word phrase or sentence, that reads the same backwards and forwards.. An example is the word wow. w o w. If you spell it backwards, it is still w o w. Another example is Madam I'm Adam. However, because of the way the computer thinks about things, I have decided to make spaces, symbols, numbers and apostrophes to not be part of the phrase... and so my program will first ask for an entry, which is parsed as a String. then it will check each index position of that word from 0 to length - 1. if there is an illegal character or space found, then a message is displayed and it will prompt the user to reenter a suitable word. As of this point, it only checks for spaces... my code compiles but when run gives a StringIndexOutOfBounds Exception after the word is entered.
My code, which can be found below, consists of two classes in two files. One is the application containing the main method, the other is the actual code.
Code Java:
public class againApp{
public static void main(String [] args){
again a = new again();
again.start();
}
}
public class again{
static boolean isPalindrome;
static boolean reEnter;
public again(){
isPalindrome = false;
reEnter = false;
}
public static void start(){
do{
System.out.println("Pleanse enter the word or phrase, with no spaces, to be tested ");
String word = Keyboard.readInput();
reEnter = checkWord(word);
if (reEnter){
System.out.println("Your word or phrase contain spaces or illegal characters. Please check and reenter");
}
}
while (reEnter);
if(!reEnter){
System.out.println("The word is ok");
}
}
public static boolean checkWord(String myString){
int i = 0;
for(i = 0; i < myString.length()||!reEnter; i++){
if (myString.charAt(i)==('\0')){
return true;
}
}
return false;
}
}
Re: StringIndexOutOfBounds Exception
Quote:
gives a StringIndexOutOfBounds Exception after the word is entered.
Please post the full text of the error message. It has valuable information.
Re: StringIndexOutOfBounds Exception
Code java:
for(i = 0; i < myString.length()||!reEnter; i++) {
if (myString.charAt(i)==('\0')){
With an OR statement only one of the conditions needs to be true. Since you initialise reEnter to false, not reEnter is always true. Therefore your loop will continue even when you have reached the end of the String and continue trying to get the next char. Also the if statement is not checking for a space.
Re: StringIndexOutOfBounds Exception
but if i put just the two single quotes to show i want to test for an empty character... instead of '0\' which is the empty character literal... i get a char cannot be dereferenced compiler error.
Re: StringIndexOutOfBounds Exception
Space is not an 'empty' character. A literal space character is two quotes separated by... you guessed it, a SPACE.