go to previous page   go to home page   go to next page hear noise highlighting

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.

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. The data might come from a human user, and sometimes humans make errors (this might come as a shock.)


public 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." );  
  }
}      

QUESTION 21:

Fill in the blanks.


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