Java Reference
In-Depth Information
3.10
What is wrong in the following code?
if (score >= 60.0 )
grade = 'D' ;
else if (score >= 70.0 )
grade = 'C' ;
else if (score >= 80.0 )
grade = 'B' ;
else if (score >= 90.0 )
grade = 'A' ;
else
grade = 'F' ;
3.7 Common Errors in Selection Statements
Forgetting necessary braces, ending an if statement in the wrong place, mistaking ==
for = , and dangling else clauses are common errors in selection statements.
The following errors are common among new programmers.
Key
Point
Common Error 1: Forgetting Necessary Braces
The braces can be omitted if the block contains a single statement. However, forgetting the
braces when they are needed for grouping multiple statements is a common programming
error. If you modify the code by adding new statements in an if statement without braces,
you will have to insert the braces. For example, the following code in (a) is wrong. It should
be written with braces to group multiple statements, as shown in (b).
if (radius >= 0 )
area = radius * radius * PI;
System.out.println( "The area "
+ " is " + area);
if (radius >= 0 )
area = radius * radius * PI;
System.out.println( "The area "
+ " is " + area);
{
}
(a) Wrong
(b) Correct
Common Error 2: Wrong Semicolon at the if Line
Adding a semicolon at the end of an if line, as shown in (a) below, is a common mistake.
Logic error
Empty block
if (radius >= 0 )
{
;
if (radius >= 0 )
{ }
;
{
Equivalent
area = radius * radius * PI;
System.out.println( "The area "
+ " is " + area);
area = radius * radius * PI;
System.out.println( "The area "
+ " is " + area);
}
}
(a)
(b)
This mistake is hard to find, because it is neither a compile error nor a runtime error; it is a
logic error. The code in (a) is equivalent to that in (b) with an empty block.
This error often occurs when you use the next-line block style. Using the end-of-line block
style can help prevent this error.
 
 
Search WWH ::




Custom Search