Computing the Average

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 program will compile and run. The array object will be constructed successfully (but it will have no cells and no values).

The enhanced for loop will run correctly (but it will not assign anything to val and will never execute its loop body.)

The program will print out:

The total is: 0.0 

This is a dubious claim. A better program would test for zero-length arrays and treat them as a special case. Our next program will do that.

Computing the Average

Here is the program with some additional statements for computing the average of the elements. It checks that there are more than zero elements and avoids dividing by zero.

class AverageArray
{
  public static void main ( String[] args ) 
  {
    double[] array =  { -47.39, 24.96, -1.02, 3.45, 14.21, 32.6, 19.42 } ;

    if ( array.length  0 )
    {
      // declare and initialize the total
      double  total = 0.0 ;

      // add each element of the array to the total
      for ( double x : array )
        total += x ;
        
      System.out.println("The total is:   " + total );
      System.out.println("The average is: " + total /   );
    }      
    else
      System.out.println("The array contains no elements." );  
  }
}      

You might think that it is strange to test if array contains any elements, since it is obvious that it does. However, in a more realistic program the array would come from an external source (perhaps from a file), and might contain no elements.

QUESTION 21:

Fill in the blanks.