Difference between revisions of "Out of Bounds and One off Errors"

From CompSciWiki
Jump to: navigation, search
(Added link back to array chapter page)
Line 4: Line 4:
 
array[2000] = “Hello World”;
 
array[2000] = “Hello World”;
 
*An example of a One Off error:
 
*An example of a One Off error:
 +
 
int array[] = new int[10];
 
int array[] = new int[10];
 
for(int i = 0; i <= array.length; i++)
 
for(int i = 0; i <= array.length; i++)

Revision as of 21:48, 28 November 2007

COMP 1010 Home > Arrays


Introduction

In this secion, I will teach you about ‘Out of Bounds’ and ‘One off' errors. I will explain what the errors are and how to solve them.

   

{{{Body}}}

Out of Bounds and One off Errors

(Andrew)

An Out of Bounds error is one in which the program tries to access a location in the array that does not exist. For example, in an array with 20 data locations, trying to select the 21st would cause an Out of Bounds error.

The following example displays code that will fail because of the Out of Bounds error:

String position = 20;
String array[] = new String[10];

array[position] = “Hello World”;

This will fail because the value of ‘position’ is outside the array’s boundaries. There is no way to correct this error if the value being used (in this example's case: ‘position’) is not known ahead of time. You can, however, prevent the error from occurring by checking the variable (in this case: ‘position’) before applying it.

String position = 20;
String array[] = new String[10];

if(position < array.length && position >= 0)
    array[position] = “Hello World”;
else
    System.out.println(“Error: value in ‘position’ (” + position + “) exceeds size of array ‘array’ (” + array.length + “)”);

This will result in an error message being printing rather than the operation being performed, causing the program to fail. This will also work in any of your programs where the value being checked is not known ahead of time.


A One off error is a form of an Out of Bounds error. The distinguishing feature of a One off error is that they occur as a result of an improper loop. The term ‘One off’ means that the either the loop results in the accessing of a location one over the array’s length (if it is an incremented loop) or one below (in the event of a decremented loop).


The following example displays code that will fail because of the One off error:

int array[] = new int[10];

for(int i = 0; i <= array.length; i++)
    array[i] = i;

This fails because the loop will count from 0 to 10; however, arrays are 0-relative (the very first location of the array is 0 and the last is the ‘defined length’ – 1) so the last valid data location in this case is 9. You can solve this problem by stopping the loop one element before the length by changing the condition to ‘i < array.length’.