Click to See Complete Forum and Search --> : Need some help please.


JoeyOpal
04-25-2005, 08:24 PM
Hello,

I am getting an ArrayIndexOutOfBounds error.

I cannot figure out what I am doing wrong or how I can fix it.

Thank you,
Joey


public class PalindromeCheck
{
String charString;
char[] a = new char[80];
int i;
int count = 0;
//boolean charsMatch = true;
boolean result;

//Do I want to add constructors?

//GET INPUT -------------------------------------------------
//PRECONDITION:
public void checkInput()
{
System.out.println("This program will check a string of characters");
System.out.println("and determine whether or not the string is a palindrom
e.");
System.out.println("Input a string of characters followed by a period.");
System.out.println("You must make sure that you include the period at the
end");
System.out.println("of the string or else you will not get correct results
.");
charString = SavitchIn.readLine();

if(charString.length() > 80)//makes sure the user can only enter 80 char m
ax (79 plus the period).
{
System.out.println("You cannot enter more than 79 characters (plus a peri
od)\n");
System.out.println("\nThe program will now exit.\n");
System.out.println("Please run the program again and ");
System.out.println("input the correct string of characters.\n");
System.exit(0); //should this do something different?
}

char a[] = charString.toUpperCase().toCharArray(); //converts a string to
an array of characters

for(int i = 0; i < (a.length); i++)//makes sure the input is either letter
s or blank spaces
{
if(Character.isLetter(a[i]) || Character.isSpaceChar(a[i]))
{
//Maybe check for numbers instead so the "if" statement isn't empty.
//What about symbols such as &, *, and #?
}
else
System.out.println("The input must be a letter or a white space.");
break;
}

System.out.println("\nThe string of characters you entered is: "); //error
checking
for(int i = 0; i < a.length; i++) //displays the array to the screen
{
System.out.print(a[i]);
}
System.out.println("\nIs this the correct string of characters?");
char choice = SavitchIn.readLineNonwhiteChar();
choice = Character.toUpperCase(choice);
if(choice == 'N')
{
System.out.println("\nThe program will now exit.\n");
System.out.println("Please run the program again and ");
System.out.println("input the correct string of characters.\n");
System.exit(0); //should this do something different?
}
else
for(int i = 0; i < a.length; i++)//increments int used once for each arra
y index that is used
{
count++;
}

result = palindrome(a, count);
System.out.println("\n" + (result));
if(result)
{
System.out.println(charString + " IS A PALINDROME.\n");
}
else
System.out.println(charString + " IS NOT A PALINDROME.\n");
}
//POSTCONDITION:
//-------------------------------------------------------------------------
--
//PALINDROME
//PRECONDITION: The array a contains letters and blanks in positions a[0]
through a[used-1].
//Returns true if the string is a palindrome and false otherwise.
//The program will call this method with the array and one other int variab
le.
//The other int variable keeps track of how much of the array is used (part
ially filled array).

public static boolean palindrome(char[] a, int used)
{
int left;
int right = used - 1;
for(left = 0; left < used; left++, right--)
{
if(a[left] != a[right])
{
return false;
}
}
return true;

/*
int i;
for(i = 0; i < (used / 2) ;i++)
{
if(a[i] != a[used - i - 1])
return false;
}
return true;
*/

/*
int left = 0;
int right = a.length - 2;

while(left <= right && charsMatch)
{
if(a[left] == a[right])
{
left++;
right--;
}
else
{
charsMatch = false;
}
}
*/
}
//POSTCONDITION:
//-------------------------------------------------------------------------
-
//DISPLAY ARRAY INFO
//PRECONDITION:
public void displayArrayInfo(int used)
{
System.out.println("\nCount = " + count);
System.out.println("Used = " + used);
System.out.println("\nThe length of the string without the period is " + (
charString.length()-1));
System.out.println("The number of indexes already used is " + count + ".")
; //displays the number of indexes already used
System.out.println("The lowest index used is index a[" + ((a.length-1)-(a.
length-1))); //displays the lowest index
System.out.println("The highest index used is index a[" + (a.length-1) + "
]."); //displays the highest index used
}
//POSTCONDITION:
//-------------------------------------------------------------------------
//EXIT PROGRAM
//PRECONDITION:
public void exitProgram()
{
//boolean repeat = true; //Need a (do while?) loop to continue the program
until the user wants to exit
System.out.println("\nThe program is now exiting.\n");
System.exit(0);
}
//POSTCONDITION:
//-------------------------------------------------------------------------

//MAIN MENU
//PRECONDITION:
public void mainMenu()
{
char choice;
do
{
System.out.println("\n\n\n-----------------------------------------------
-------------");
System.out.println("-----------------------------------------------------
-------");
System.out.println("------This is the main menu. Please make a selection
.------\n");
System.out.println("Please press [1] to input a character string.");
System.out.println("Please press [2] to display array info.");
System.out.println("Please press [3] to exit the program.");

choice = SavitchIn.readLineNonwhiteChar();

switch(choice)
{
case '1': checkInput();
break;

case '2': if(charString == null)
{
System.out.println("\nYou must use option 1 first.\n");
break;
}
displayArrayInfo(count); //gives NullPointerException if this is cho
sen first
break;

case '3': exitProgram();
break;

default: System.out.println("Options 1-3 only please.");
System.out.println("Please enter a selection.\n");
//break;
}
}while(choice != '3');
}
//POSTCONDITION:
//----------------------------------------------------------------------
//MAIN
//PRECONDITION:
public static void main(String[] args)
{
PalindromeCheck checkIt = new PalindromeCheck();
checkIt.mainMenu();
}
//POSTCONDITION:
}

buntine
04-25-2005, 08:53 PM
This is happening because you are trying to access an array index that does not exist. Which line is the error occuring on?

JoeyOpal
04-25-2005, 09:08 PM
Here is the error:

java.lang.ArrayIndexOutOfBoundsException: 5
at PalindromeCheck.palindrome(PalindromeCheck.java:90)
at PalindromeCheck.checkInput(PalindromeCheck.java:67)
at PalindromeCheck.mainMenu(PalindromeCheck.java:168)
at PalindromeCheck.main(PalindromeCheck.java:195)

JoeyOpal
04-25-2005, 10:07 PM
Can anyone help me figure this out?

Thanks,
Joey

buntine
04-26-2005, 12:17 AM
The error is being caused because you are try to access a member of the character array call a.

This is where the error is occuring:

if(a[left] != a[right])
{
return false;
}

You need to simplify the process and use some debugging techniques to see exactly why the rror is occuring. Its too confusing with all the increment and decrementing variables for me to simply provide an answer to you.

There is alot of dead code within this example. By that, I mean that alot of code is unnecessary. I suggest you re-think your logic and rewrite this class.

Regards.

JoeyOpal
04-26-2005, 12:56 AM
I am in the process of rewriting the code. Here is what I have so far. I think I am on the right track.


public class Palindrome7
{
String charString;
int i;
int count;

//checkInput method
public void checkInput()
{
count = 0;
System.out.println("This program will check a string of characters");
System.out.println("and determine whether or not the string is a palindrome.");
System.out.println("Input a string of characters followed by a period.");
System.out.println("You must make sure that you include the period at the end");
System.out.println("of the string or else you will not get correct results.");
charString = SavitchIn.readLine();

if(charString.length() > 80)//makes sure the user can only enter 80 char max (79 plus the period).
{
System.out.println("You cannot enter more than 79 characters (plus a period)\n");
System.out.println("\nThe program will now exit.\n");
System.out.println("Please run the program again and ");
System.out.println("input the correct string of characters.\n");
System.exit(0); //should this do something different?
}

charString = charString.toLowerCase(); //this makes the string all lower case.

char[] a = new char[80];


//Make sure the input is only letters and blank spaces


//Puts the charString into the array.
for(i = 0; charString.charAt(i) != '.'; i++) //the loop stops when you encounter a period.
{
if(charString.charAt(i) != ' ') //ignore the space
{
a[count] = charString.charAt(i); //use count as the array index
count++;
}
}

//Echos back input
System.out.println("\nThe string of characters you entered is: "); //error checking
for(i = 0; i < count; i++) //displays the array to the screen
{
System.out.print(a[i]);
}

System.out.println("\nIs this the correct string of characters?");
char choice = SavitchIn.readLineNonwhiteChar();
choice = Character.toUpperCase(choice);
if(choice == 'N')
{
System.out.println("\nThe program will now exit.\n");
System.out.println("Please run the program again and ");
System.out.println("input the correct string of characters.\n");
System.exit(0); //should this do something different?
}

//Checks for palindrome
boolean isPalindrome = palindrome(a,count);
System.out.println(isPalindrome);
if(isPalindrome)
{
System.out.println(charString + " IS A PALINDROME.\n");
}
else
System.out.println(charString + " IS NOT A PALINDROME.\n");
}

//palindrome method
public static boolean palindrome(char[] a, int used)
{
int i;
for(i = 0; i < (used / 2); i++)
{
if(a[i] != a[used-i-1])
return false;
}
return true;
}


//displayArrayInfo method



//exitProgram method
public void exitProgram()
{
System.out.println("\nThe program is now exiting.\n");
System.exit(0);
}

//mainMenu method
public void mainMenu()
{
char choice;
do
{
System.out.println("\n\n------------------------------------------------------------");
System.out.println("------------------------------------------------------------");
System.out.println("------This is the main menu. Please make a selection.------\n");
System.out.println("Please press [1] to input a character string.");
System.out.println("Please press [2] to display array info.");
System.out.println("Please press [3] to exit the program.");

choice = SavitchIn.readLineNonwhiteChar();

switch(choice)
{
case '1': checkInput();
break;

case '2': if(charString == null)
{
System.out.println("\nYou must use option 1 first.\n");
break;
}
//displayArrayInfo(a, used, count); //gives NullPointerException if this is chosen first
break;

case '3': exitProgram();
break;

default: System.out.println("Options 1-3 only please.");
System.out.println("Please enter a selection.\n");
//break;
}
}while(choice != '3');
}

//main method
public static void main(String[] args)
{
Palindrome7 checkIt = new Palindrome7();
checkIt.mainMenu();
}
}

buntine
04-26-2005, 01:22 AM
OK, starting to look better already.

JoeyOpal
04-26-2005, 03:21 AM
OK, now I have a few questions.

How do I:

Make sure the input is only letters and blank spaces?
Make sure there is a period at the end of the charString?
If the user inputs the wrong string, how do I allow the user to stay in the program to reinput the correct string?


public class Palindrome7
{
String charString;
int i;
int count;
//int used;
char[] a = new char[80];

//checkInput method-----------------------------------------------------------
public void checkInput()
{
count = 0; //Gives ArrayIndexOutOfBounds error if this is not here
System.out.println("This program will check a string of characters");
System.out.println("and determine whether or not the string is a palindrome.");
System.out.println("Input a string of characters followed by a period.");
System.out.println("You must make sure that you include the period at the end");
System.out.println("of the string or else you will not get correct results.");
charString = SavitchIn.readLine();

if(charString.length() > 80)//makes sure the user can only enter 80 char max (79 plus the period).
{
System.out.println("You cannot enter more than 79 characters (plus a period)\n");
System.out.println("\nThe program will now exit.\n");
System.out.println("Please run the program again and ");
System.out.println("input the correct string of characters.\n");
System.exit(0); //should this do something different?
}

charString = charString.toLowerCase(); //this makes the string all lower case.


//!!!Make sure the input is only letters and blank spaces
//!!!Make sure there is a period at the end of the charString


//Puts the charString into the array.
for(i = 0; charString.charAt(i) != '.'; i++) //the loop stops when you encounter a period.
{
if(charString.charAt(i) != ' ') //ignore the space
{
a[count] = charString.charAt(i); //use count as the array index
count++;
}
}

//Echos back input
System.out.println("\nThe string of characters you entered is: "); //error checking
for(i = 0; i < count; i++) //displays the array to the screen
{
System.out.print(a[i]);
}

System.out.println("\nIs this the correct string of characters?");
char choice = SavitchIn.readLineNonwhiteChar();
choice = Character.toUpperCase(choice);
if(choice == 'N')
{
System.out.println("\nThe program will now exit.\n");
System.out.println("Please run the program again and ");
System.out.println("input the correct string of characters.\n");
System.exit(0); //should this do something different?
}

//Checks for palindrome
boolean isPalindrome = palindrome(a,count);
System.out.println("\n");
if(isPalindrome)
{
System.out.println((isPalindrome) + " THE STRING: " + charString + " IS A PALINDROME.\n");
}
else
System.out.println((isPalindrome) + " THE STRING: " + charString + " IS NOT A PALINDROME.\n");
}

//palindrome method-----------------------------------------------------------
public static boolean palindrome(char[] a, int used)
{
int i;
for(i = 0; i < (used / 2); i++)
{
if(a[i] != a[used-i-1])
return false;
}
return true;
}

//displayArrayInfo method-----------------------------------------------------
public void displayArrayInfo(char[] a, int used)
{
System.out.println("\nThe length of the string without the period is " + (used));
System.out.println("The number of indexes already used is " + (used + 1) + "."); //displays the number of indexes already used
System.out.println("The lowest index used is index a[" + ((a.length-1)-(a.length-1)) + "]."); //displays the lowest index
System.out.println("The highest index used is index a[" + (a.length-1) + "]."); //displays the highest index used
}

//exitProgram method----------------------------------------------------------
public void exitProgram()
{
System.out.println("\nThe program is now exiting.\n");
System.exit(0);
}

//mainMenu method-------------------------------------------------------------
public void mainMenu()
{
char choice;
do
{
System.out.println("\n\n------------------------------------------------------------");
System.out.println("------------------------------------------------------------");
System.out.println("------This is the main menu. Please make a selection.------\n");
System.out.println("Please press [1] to input a character string.");
System.out.println("Please press [2] to display array info.");
System.out.println("Please press [3] to exit the program.");

choice = SavitchIn.readLineNonwhiteChar();

switch(choice)
{
case '1': checkInput();
break;

case '2': if(charString == null)
{
System.out.println("\nYou must use option 1 first.\n");
break;
}
displayArrayInfo(a, count); //gives NullPointerException if this is chosen first
break;

case '3': exitProgram();
break;

default: System.out.println("Options 1-3 only please.");
System.out.println("Please enter a selection.\n");
//break;
}
}while(choice != '3');
}

//main method-----------------------------------------------------------------
public static void main(String[] args)
{
Palindrome7 checkIt = new Palindrome7();
checkIt.mainMenu();
}
}

buntine
04-26-2005, 04:38 AM
You can use a Regular Expression to validate the string. It can be a rather complex area of programming if you really delve into it (there are several books devoted solely to writing Regular Expressions), but what you need to do should be relatively simple. There is a RegEx package built into Java that is quite handy.

private Pattern pattern;
private Matcher matcher;

pattern = Pattern.compile("^[a-zA-Z.]$"); // << This is your Regular Expression.
matcher = pattern.matcher(charString);

if (matcher.find())
// Is valid.
else
// Is NOT valid!

To ensure the last character in a period, you can simply grab the last character and then find out what it is.

String lastChar = charString.substring(charString.length-1, charString.length);
if (!lastChar.equals("."))
// Not a period!
else
// Is a period.

To continue the process until a valid string is entered, you can use a while loop.

private Pattern pattern;
private Matcher matcher;
pattern = Pattern.compile("^[a-zA-Z.]$"); // << This is your Regular Expression.
matcher = pattern.matcher(charString);
String lastChar = charString.substring(charString.length-1, charString.length);

while (!lastChar.equals(".") && !matcher.find())
{
// A code block.
}

Hopefully, this will help you out a bit.

Regards.

JoeyOpal
04-26-2005, 04:45 AM
I don't want to use regular expressions because I haven't learned about that yet. I am trying to use only the things that I have learned so far.

I am still having some problems. I belive I am having problems with the two statements that I now have commented out:

if(charString.charAt(i) != '.')

and

for(i = 0; i < count; i++)//makes sure the input is only letters and blank spaces

I am getting this error if I leave these two statements:

java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(Unknown Source)
at Palindrome7.checkInput(Palindrome7.java:29)
at Palindrome7.mainMenu(Palindrome7.java:127)
at Palindrome7.main(Palindrome7.java:158)
Exception in thread "main"



public class Palindrome7
{
String charString;
int i;
int count;
//int used;
char[] a = new char[80];

//checkInput method-----------------------------------------------------------
public void checkInput()
{
count = 0; //Gives ArrayIndexOutOfBounds error if this is not here
System.out.println("This program will check a string of characters");
System.out.println("and determine whether or not the string is a palindrome.");
System.out.println("Input a string of characters followed by a period.");
System.out.println("You must make sure that you include the period at the end");
System.out.println("of the string or else you will not get correct results.");
charString = SavitchIn.readLine();

if(charString.length() > 80)//makes sure the user can only enter 80 char max (79 plus the period).
{
System.out.println("\n\nPlease input the correct string of characters.\n ");
error();
}

charString = charString.toLowerCase(); //this makes the string all lower case.

//Puts the charString into the array.
for(i = 0; charString.charAt(i) != '.'; i++) //the loop stops when you encounter a period.
{
if(charString.charAt(i) != ' ') //ignore the space
{
a[count] = charString.charAt(i); //use count as the array index
count++;
}
}

/*
if(charString.charAt(i) != '.')
{
System.out.println("\n\nPlease input the correct string of characters.\n ");
error();
}
*/

/*
for(i = 0; i < count; i++)//makes sure the input is only letters and blank spaces
{
if(Character.isDigit(a[i]))
{
System.out.println("\n\nPlease input the correct string of characters.\n ");
error();
}
}
*/

//Echos back input
System.out.println("\nThe string of characters you entered is: "); //error checking
for(i = 0; i < count; i++) //displays the array to the screen
{
System.out.print(a[i]);
}

System.out.println("\nIs this the correct string of characters?");
char choice = SavitchIn.readLineNonwhiteChar();
choice = Character.toUpperCase(choice);
if(choice == 'N')
{
System.out.println("\n\nPlease input the correct string of characters.\n ");
error();
}

//Checks for palindrome
boolean isPalindrome = palindrome(a,count);
System.out.println("\n");
if(isPalindrome)
{
System.out.println((isPalindrome) + " THE STRING: " + charString + " IS A PALINDROME.\n");
}
else
System.out.println((isPalindrome) + " THE STRING: " + charString + " IS NOT A PALINDROME.\n");
}

//palindrome method-----------------------------------------------------------
public static boolean palindrome(char[] a, int used)
{
int i;
for(i = 0; i < (used / 2); i++)
{
if(a[i] != a[used-i-1])
return false;
}
return true;
}

//displayArrayInfo method-----------------------------------------------------
public void displayArrayInfo(char[] a, int used)
{
System.out.println("\nThe length of the string without the period is " + (used));
System.out.println("The number of indexes already used is " + (used + 1) + "."); //displays the number of indexes already used
System.out.println("The lowest index used is index a[" + ((a.length-1)-(a.length-1)) + "]."); //displays the lowest index
System.out.println("The highest index used is index a[" + (a.length-1) + "]."); //displays the highest index used
}

//exitProgram method----------------------------------------------------------
public void exitProgram()
{
System.out.println("\nThe program is now exiting.\n");
System.exit(0);
}

//mainMenu method-------------------------------------------------------------
public void mainMenu()
{
char choice;
do
{
System.out.println("\n\n------------------------------------------------------------");
System.out.println("------------------------------------------------------------");
System.out.println("------This is the main menu. Please make a selection.------\n");
System.out.println("Please press [1] to input a character string.");
System.out.println("Please press [2] to display array info.");
System.out.println("Please press [3] to exit the program.");

choice = SavitchIn.readLineNonwhiteChar();

switch(choice)
{
case '1': checkInput();
break;

case '2': if(charString == null)
{
System.out.println("\nYou must use option 1 first.\n");
break;
}
displayArrayInfo(a, count); //gives NullPointerException if this is chosen first
break;

case '3': exitProgram();
break;

default: System.out.println("Options 1-3 only please.");
System.out.println("Please enter a selection.\n");
//break;
}
}while(choice != '3');
}

//error method----------------------------------------------------------------
public void error()
{
checkInput();
}

//main method-----------------------------------------------------------------
public static void main(String[] args)
{
Palindrome7 checkIt = new Palindrome7();
checkIt.mainMenu();
}
}