Reputation: 111
I have written a program with a lot of operations on arrays. How I can check if I out of range with array, because I go Run Time Error at SPOJ.
Upvotes: 2
Views: 9688
Reputation: 3822
Without knowing any more detailed context, the basic approach as outlined by Jon Skeet in the comments is something like the following:
if (index < 0 || index >= array.length) {
//Index Out Of Range
}
Upvotes: 5
Reputation: 3651
There is no code to refer and see if you have gone out of range. Maybe you want to post your code for reference.
As long as your index is not of negative value and 1 value under the length of your array, you will be within bounds of your array.
For example an array of length 10, you have to minus 1 and able to call indexes between 0 - 9.
for(int x=0; x < yourArray.length; x++){
//this for loop will nicely loop without going out of bounds unless your
//loop body contains something that will trigger the error.
}
Upvotes: 0