Java Reference
In-Depth Information
15
16
Print the number of passes
17
Print the number of failures
18
19
If more than eight students passed
20
Print “Bonus to instructor!”
Fig. 4.11 | Pseudocode for examination-results problem. (Part 2 of 2.)
The Java class that implements the pseudocode algorithm and two sample executions
are shown in Fig. 4.12. Lines 13, 14, 15 and 22 of main declare the variables that are used
to process the examination results.
Error-Prevention Tip 4.5
Initializing local variables when they're declared helps you avoid any compilation errors
that might arise from attempts to use uninitialized variables. While Java does not require
that local-variable initializations be incorporated into declarations, it does require that
local variables be initialized before their values are used in an expression.
1
// Fig. 4.12: Analysis.java
2
// Analysis of examination results using nested control statements.
3
import java.util.Scanner; // class uses class Scanner
4
5
public class Analysis
6
{
7
public static void main(String[] args)
8
{
9
// create Scanner to obtain input from command window
10
Scanner input = new Scanner(System.in);
11
12
// initializing variables in declarations
int passes = 0 ;
int failures = 0 ;
int studentCounter = 1 ;
13
14
15
16
17
// process 10 students using counter-controlled loop
18
while (studentCounter <= 10 )
19
{
20
// prompt user for input and obtain value from user
21
System.out.print( "Enter result (1 = pass, 2 = fail): " );
22
int result = input.nextInt();
23
24
// if...else is nested in the while statement
if (result == 1 )
passes = passes + 1 ;
else
failures = failures + 1 ;
25
26
27
28
29
Fig. 4.12 | Analysis of examination results using nested control statements. (Part 1 of 2.)
 
Search WWH ::




Custom Search