We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Basic Question: ArrayIndexOutOfBoundsException: 0
Page Index Toggle Pages: 1
Basic Question: ArrayIndexOutOfBoundsException: 0 (Read 742 times)
Basic Question: ArrayIndexOutOfBoundsException: 0
Oct 29th, 2009, 3:22am
 
Hi there,

i'm currently around with arrays, coming from a php-background.
so there is alot different in handling array's in processing then in php.
i did a rather small thing to learn arrays but i always get an ArrayIndexOutOfBoundsException: 0 on line 10.
can anybody explain me what i'm doing wrong?
Code:
int num;
int[] ints;

num = 0;
ints = new int[num];
println(ints.length);

for(int i = 0;i <= 50;i++)
{
ints[i] = int(random(0,100));
println(ints[i]);
}
Re: Basic Question: ArrayIndexOutOfBoundsException: 0
Reply #1 - Oct 29th, 2009, 3:30am
 
Hi, someone correct me if there is better way to solve this

First I think you need to initialize the array with the number of items you will use in the for loop

Second the for loop cant look the array if the condition is set to <= because it will loop 51 times

Code:
int num;
int[] ints;

num = 50;
ints = new int[num];
println(ints.length);

for(int i = 0; i < num;i++)
{
 ints[i] = int(random(0,100));
 println(ints[i]);
}


Have a look in to arrayList as well, they are more "dynamic"

Cheers
rS
Re: Basic Question: ArrayIndexOutOfBoundsException: 0
Reply #2 - Oct 29th, 2009, 3:42am
 
Exactly as nardove said.  The '<=' is why you're getting an outOfBounds error since it will try and access ints[50] which, since array indices start at 0, doesn't exist.

You can also use shortcuts on variable declarations and should avoid the use of 'magic numbers':

Code:
int arrayLength = 50;
int[] ints = new int[arrayLength];
println("length: " + ints.length);

// Either use arrayLength or ints.length as the limit:
for(int i = 0;i < arrayLength; i++) {
 ints[i] = int(random(0,100));
 println(i + ": " + ints[i]);
}
Page Index Toggle Pages: 1