Java Reference
In-Depth Information
13 double magnitude = in.nextDouble();
14 Earthquake quake = new
Earthquake(magnitude);
15 System.out.println(quake.getDescription())
;
16 }
17 }
194
195
Output
Enter a magnitude on the Richter scale: 7.1
Many buildings destroyed
Here we must sort the conditions and test against the largest cutoff first. Suppose
we reverse the order of tests:
if (richter >= 0) // Tests in wrong order
r = "Generally not felt by people";
else if (richter >= 3.5)
r = "Felt by many people, no destruction";
else if (richter >= 4.5)
r = "Damage to poorly constructed buildings";
else if (richter >= 6.0)
r = "Many buildings considerably damaged, some
collapse";
else if (richter >= 7.0)
r = "Many buildings destroyed";
else if (richter >= 8.0)
r = "Most structures fall";
This does not work. All nonnegative values of richter fall into the first case, and
the other tests will never be attempted.
In this example, it is also important that we use an if/else/else test, not just
multiple independent if statements. Consider this sequence of independent tests:
if (richter >= 8.0) // Didn't use else
r = "Most structures fall";
if (richter >= 7.0)
r = "Many buildings destroyed";
if (richter >= 6.0)
r = "Many buildings considerably damaged, some
collapse";
if (richter >= 4.5)
Search WWH ::




Custom Search