Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why won't this for loop work?

 
colton peterson
Ranch Hand
Posts: 97
Linux Python VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is supposed to be simple coloring book program, but I can't find out why it is giving me errors.



This is the output

we're in main
setting up gui
getting images
setting up ImageList
Loop is 0 out of 0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at CustomPaint.UniCode.getImageList(CustomPaint.java:84)
at CustomPaint.UniCode.setUpGui(CustomPaint.java:40)
at CustomPaint.CustomPaint.main(CustomPaint.java:16)

Process completed.

I am pretty sure the for loop in getImageList is throwing the error.
The file dir declared at the beginning is real and the folder it is reffering to has two files, test.gif and test2.gif KcolorChooser is another class in a different file it compiles and runs fine. FloodFill is a flood filling algorithm that I tested and it also works fine.
Any help would be appreciated.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, this line is wrong:

for(int i = 0; i <= dirFiles.length; i++) {

If an array has X elements, then a for loop like

for(int i = 0; i <X; i++) {

will visit each element once. Note the "<" rather than "<=". The last element of the array is at index X-1.

Now, the error message suggests that element 0 is out of bounds -- i.e., that there are no files in the list. This is at odds with what you're telling me, so something's not right. One thing you might try: convert the filename to lower case (using String.toLowerCase()) before checking for .gif; although Windows filenames aren't case-sensitive, Java Strings are.
 
colton peterson
Ranch Hand
Posts: 97
Linux Python VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. This forum rocks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic