Use Nested-ifs when Needed

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:

int count = 0;  
int total = 345; 

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

}
else
  System.out.println("No values to average.");

Use Nested-ifs when Needed

In this code fragment, the "guard" that prevents division by zero is the first if statement. When count is zero, it prevents the true-branch from executing.

It is easy to get caught up in complicated boolean expressions and to use them when a nested-if is more appropriate. Notice that the solution to the question is probably the better program because it is easier to understand and writes better messages to the monitor.


QUESTION 7:

What is the true/false value of:

12 > 6 || 18 > 1