We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I am trying to populate an array with all of the x values I am going to be using in a program, but it keeps returning an error saying that my array is empty
this is a global variable at the top of my code:
int x_length = (width/25);
this is the for loop I am using to try and fill all of the iterations of the array. I am ultimately trying to create 25 different points along the x axis that are spaced at a distance of (width/25) from one to the other
int[] x_points = new int[x_length];
for (int i=0; i <= 25; i++) {
x_points[i] = x_length * i;
println("int val : x_points");
}
when I run the code, the program works for about 2 seconds and then highlights 'x_points[i] = x_length * i;' and returns the ArrayIndexOutOfBoundsException: 0 message, but i am having trouble figuring out why it's saying my array is empty?
Answers
The problem is because the for-loop assumes that there will be 26 elements (0 to 25 inclusive) in the array change the loop to
The
length
field of an array always holds the number of elements in it so it is a safe way to limit the array index to prevent ArrayIndexOutOfBoundsExceptionOkay thanks that helps, I don't get any error messages when I replace with your suggestion, but for some reason the for loop is never being initialized. It could be because I am using that for loop to iterate the values within the array x_points so it starts with a value of zero and therefor never starts... so I changed the test statement to be =< and the for loop initializes...
and then I am back to where I started, I get the same error message, OutOfBoundsException: 0, on the
'x_points[i] = x_length * i;' line again
It means the array is 0-length! You need to specify a bigger size than that when creating the array! :-\"
int x_length = (width/25);
At the top of your code
width
has the value 0 so you end up with a zero length array. Change this line toint x_length;
THEN include the statement
x_length = (width/25);
in the setup function AFTER you have called the size(...) functionTHEN change the loop back to my previous post, do NOT use
<=
otherwise you will get the ArrayIndexOutOfBoundsException back