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

Answer:

Poor Average


Testing Values

Sometimes an if statement or a while statement uses the short-circuit AND to avoid division by zero, or to avoid some other easily tested condition, as in the example. The same could be done with nested if statements, but with additional clutter that the programmer might wish to avoid. The first comparison, count > 0 acts like a guard that prevents evaluation from reaching the division when count is zero.

int count = 0;  
int total = 345; 

if ( count > 0 && total / count > 80 )
  System.out.println("Acceptable Average");
else
  System.out.println("Poor Average");

This code fragment would not work if the non-short-circuit AND ( & ) were used. The second operand would attempt a division by zero even when the first operand evaluated to false. The example works like this:

int count = 0;  
int total = 345; 

if ( count > 0 && total / count > 80 )
     ---------
     false, so no further 
     evaluation is done.

QUESTION 6:

Re-write the example using nested if statements:

int count = 0;  
int total = 345; 

if (  )
{
  if (  )
    System.out.println("Acceptable Average");
  else
    System.out.println("Low Average");
}
else
  System.out.println("No values to average.");