Java Reference
In-Depth Information
The correct program is as follows:
//GPA program without bugs.
import
java.util.*;
//Line 1
public class
GPABugProgCorrect
//Line 2
{
//Line 3
static
Scanner console =
new
Scanner(System.in);
//Line 4
public static void
main(String[] args)
//Line 5
{
//Line 6
4
double
gpa;
//Line 7
System.out.print("Enter the GPA: ");
//Line 8
gpa = console.nextDouble();
//Line 9
System.out.println();
//Line 10
if
(gpa >= 2.0)
//Line 11
{
//Line 12
if
(gpa >= 3.9)
//Line 13
System.out.println("Dean\'s Honor List.");
//Line 14
}
//Line 15
else
//Line 16
System.out.println("The GPA is below the "
+ " graduation requirement. \nSee your
"
+ "academic advisor.");
//Line 17
}
//Line 18
}
//Line 19
Sample Runs: (In these sample runs, the user is shaded.)
Sample Run 1:
Enter the GPA: 3.91
Dean's Honor List.
Sample Run 2:
Enter the GPA: 3.8
Sample Run 3:
Enter the GPA: 1.95
The GPA is below the graduation requirement.
See your academic advisor.
In cases such as this one, the general rule is that you cannot look inside a block (that is,
inside the braces) to pair an
else
with an
if
. The
else
in Line 16 cannot be paired with
the
if
in Line 13 because the
if
statement in Line 13 is enclosed within braces, and the
else
in Line 16 cannot look inside those braces. Therefore, the
else
in Line 16 is paired
with the
if
in Line 11.
Search WWH ::
Custom Search