File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes ArrayIndexOutOfBoundsException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ArrayIndexOutOfBoundsException" Watch "ArrayIndexOutOfBoundsException" New topic
Author

ArrayIndexOutOfBoundsException

Mick Flynn
Greenhorn

Joined: May 09, 2001
Posts: 8
Hi there,
Here's the code where I'm having the problem:
StringTokenizer st = new StringTokenizer (inputString, ";");
String wordArray [] = new String [numberOfTokens];
for (int count = 0; count < numberOfTokens; count++)
{
wordArray [count] = st.nextToken();
}
This generates an ArrayIndexOutOfBoundsException. Does anyone have any idea why? The SDK documentation says that it is normally caused by an array index being negative or too high for the array.
But this shouldn't be the case here, should it? I mean, wordArray should never be higher than the number of tokens in st, should it?
Any ideas or comments? Thanks!!
Scott Appleton
Ranch Hand

Joined: May 07, 2001
Posts: 195
Mick, it's not apparent how your numberOfTokens property is being calculated. Is your example missing a line of code such as
int numberOfTokens = st.countTokens();
?
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4456
    
    6

What is the value of numberOfTokens? Is it a local variable? Is it an instance variable?
Assuming that numberOfTokens is properly initialized, the only exception I see you getting with the code is NoSuchElementException thrown by nextToken(). You can guard against this exception by adding a check for st.hasMoreTokens() in the for-loop condition.
Junilu


Junilu - [How to Ask Questions] [How to Answer Questions]
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

And besides this... don't use a for loop if you don't have to. Investiage the API for StringTokenizer, and look for " hasMoreTokens() " and think 'while' loop.
Mick Flynn
Greenhorn

Joined: May 09, 2001
Posts: 8
Scott, Junilu,
Sorry about that, I forgot to include the line:
int numberOfTokens = st.countTokens ();
(which you guessed correctly by the way).
And it throws this beauty:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at CardSet.<init>(FlashCardViewer.java:277)
at FlashCardViewer.importFile(FlashCardViewer.java:194)
at FlashCardViewer.<init>(FlashCardViewer.java:127)
at FlashCardViewer.main(FlashCardViewer.java:133)
Any ideas?
Bob Graffagnino
Ranch Hand

Joined: May 30, 2001
Posts: 81
I tested the code in the original post and it worked fine. My guess is that the conditional statement in your for loop is "count <= numberOfTokens" instead of "count < numberOfTokens".
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: ArrayIndexOutOfBoundsException