Improved Method

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
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?