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

From CompSciWiki
Jump to: navigation, search
(fixed the first example. position was supposed to be an int instead of a String)
Line 11: Line 11:
  
 
<pre>
 
<pre>
String position = 20;
+
int position = 20;
 
String array[] = new String[10];
 
String array[] = new String[10];
  

Revision as of 20:16, 5 December 2007

COMP 1010 Home > Arrays


Introduction

This section will cover 'Out of Bounds' errors and 'One Off' errors. A brief introduction to these concepts as well as their use and significance will be covered below.

   

{{{Body}}}

Out of Bounds and One off Errors

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:

int 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’.