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