• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayIndexOutOfBoundsException

 
Mick Flynn
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 195
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 6547
21
Java Linux Mac Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 81
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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".
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic