2

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.

3
  • 5
    Well the valid range of indexes is always 0 (inclusive) to array.length (exclusive). Commented Mar 16, 2014 at 21:22
  • So many unknowns here. I bet some people dont know what SPOJ is, and what Run Time Error at SPOJ means. It many not be a problem with array indexes but many other reason. Commented Mar 16, 2014 at 21:28
  • Checking the bounds is a solution. Why you're getting errors when indexing into arrays may be indicative of a bigger problem, with which we would need more code to analyze to give you a more complete solution. Commented Mar 16, 2014 at 21:43

2 Answers 2

5

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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. 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.