File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Why won't this for loop work? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why won Watch "Why won New topic

Why won't this for loop work?

colton peterson
Ranch Hand

Joined: Nov 18, 2007
Posts: 97

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(
at CustomPaint.UniCode.setUpGui(
at CustomPaint.CustomPaint.main(

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

Joined: Jul 08, 2003
Posts: 24199

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.

[Jess in Action][AskingGoodQuestions]
colton peterson
Ranch Hand

Joined: Nov 18, 2007
Posts: 97

Thanks. This forum rocks!
I agree. Here's the link:
subject: Why won't this for loop work?
It's not a secret anymore!