Java Reference
In-Depth Information
if (richter <= 4)
System.out.println(ÐThe earthquake is
harmlessÑ);
else // Pitfall!
System.out.println(ÐNegative value not
allowedÑ);
The indentation level seems to suggest that the else is grouped with the test
richter > = 0 . Unfortunately, that is not the case. The compiler ignores all
indentation and follows the rule that an else always belongs to the closest if ,
like this:
if (richter >= 0)
if (richter <= 4)
System.out.println("The earthquake is
harmless");
else // Pitfall!
System.out.println("Negative value not
allowed");
That isn't what we want. We want to group the else with the first if . For that,
we must use braces.
if (richter >= 0)
{
if (richter <= 4)
System.out.println(ÐThe earthquake is
harmlessÑ);
}
else
System.out.println(ÐNegative value not
allowedÑ);
To avoid having to think about the pairing of the else , we recommend that you
always use a set of braces when the body of an if contains another if . In the
following example, the braces are not strictly necessary, but they help clarify the
code:
if (richter >= 0)
{
if (richter <= 4)
System.out.println(ÐThe earthquake is
harmlessÑ);
else
Search WWH ::




Custom Search