Testing Values

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   hear noise   go to next page

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");

The example program would not work if the non-short-circuit AND ( & ) were used. The second operand would include 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.");