go to previous page   go to home page   go to next page

Answer:

The improvements are seen below.

Improved Method

Since methods can be used many times with different data, it is often worthwhile to have them check for errors. This might prevent your program from crashing at a crucial time. Here is the improved printRange():

class ArrayOps
{
  . . .

  // print elements start through end
  void printRange ( int[] x, int start, int end )
  {
    for ( int index=start; index <= end && index >= 0 && index < x.length; index++  )
      System.out.print( x[index] + " " );
    System.out.println();
  }

}

This method merely returns to the caller when it detects an error. An even better method would throw an exception when it detected an error. The caller would then be alerted to the error and could do something about it (or could ignore it). Exceptions are covered in a later chapter.

QUESTION 13:

(Program Design Question: ) Do you think that this method should print out an error message when it detects an error?