2005 pearson education, inc. all rights reserved. 1 part 2 control statements
Post on 22-Dec-2015
220 views
TRANSCRIPT
2005 Pearson Education, Inc. All rights reserved.
1
Part 2
Control Statements
2005 Pearson Education, Inc. All rights reserved.
2
OBJECTIVES
In this Part you will learn:
To use the if and if else selection statements to choose among alternative actions.
To use the while repetition statement to execute statements in a program repeatedly.
To use counter-controlled repetition and sentinel-controlled repetition.
To use the assignment, increment and decrement operators.
2005 Pearson Education, Inc. All rights reserved.
3
Sequence structure activity diagram.
Solid circle represents the activity’s initial state
Solid circle surrounded by a hollow circle represents the activity’s final state
2005 Pearson Education, Inc. All rights reserved.
4
Control Structures (Cont.)
• Selection Statements– if statement
• Single-selection statement
– if…else statement• Double-selection statement
– switch statement• Multiple-selection statement
2005 Pearson Education, Inc. All rights reserved.
5
Control Structures (Cont.)
• Repetition statements– Also known as looping statements
– Repeatedly performs an action while its loop-continuation condition remains true
– while statement• Performs the actions in its body zero or more times
– do…while statement• Performs the actions in its body one or more times
– for statement• Performs the actions in its body zero or more times
2005 Pearson Education, Inc. All rights reserved.
6
if Single-Selection Statement
•if statements– Execute an action if the specified condition is true
– Can be represented by a decision symbol (diamond) in a UML activity diagram
• Transition arrows out of a decision symbol have guard conditions
– Workflow follows the transition arrow whose guard condition is true
2005 Pearson Education, Inc. All rights reserved.
7
Fig. 4.2 | if single-selection statement UML activity diagram.
Diamonds
Decision symbols (explained in section 4.5)
2005 Pearson Education, Inc. All rights reserved.
8
if…else Double-Selection Statement
•if…else statement– Executes one action if the specified condition is true or a
different action if the specified condition is false
if else double-selection statement UML activity diagram.
2005 Pearson Education, Inc. All rights reserved.
9
if ( testScore < 70 )
JOptionPane.showMessageDialog(null, "You did not pass" );
else
JOptionPane.showMessageDialog(null, "You did pass " );
Syntax for the if Statementif ( <boolean expression> )
<then block>
else
<else block>
Then BlockThen Block
Else BlockElse Block
Boolean ExpressionBoolean Expression
2005 Pearson Education, Inc. All rights reserved.
10
Control Flow
JOptionPane.showMessageDialog(null, "You did pass");
JOptionPane.showMessageDialog(null, "You did pass");
falsetestScore < 70 ?
testScore < 70 ?
JOptionPane.showMessageDialog(null, "You did not pass");
JOptionPane.showMessageDialog(null, "You did not pass");
true
2005 Pearson Education, Inc. All rights reserved.
11
testScore < 80
testScore * 2 >= 350
30 < w / (h * h)
x + y != 2 * (a + b)
2 * Math.PI * radius <= 359.99
Relational Operators
< //less than
<= //less than or equal to
== //equal to
!= //not equal to
> //greater than
>= //greater than or equal to
2005 Pearson Education, Inc. All rights reserved.
12
Decision Making: Equality and Relational Operators
• Condition– Expression can be either true or false
•if statement– Simple version in this section, more detail later
– If a condition is true, then the body of the if statement executed
– Control always resumes after the if statement
– Conditions in if statements can be formed using equality or relational operators (next slide)
2005 Pearson Education, Inc. All rights reserved.
13
Fig. 14 | Equality and relational operators.
Standard algebraic equality or relational operator
Java equality or relational operator
Sample Java condition
Meaning of Java condition
Equality operators == x == y x is equal to y != x != y x is not equal to y Relational operators > x > y x is greater than y < x < y x is less than y >= x >= y x is greater than or equal to y ≤ <= x <= y x is less than or equal to y
2005 Pearson Education, Inc. All rights reserved.
14
if ( testScore < 70 )
JOptionPane.showMessageDialog(null, "You did not pass" );
else
JOptionPane.showMessageDialog(null, "You did pass " );
Syntax for the if Statementif ( <boolean expression> )
<then block>
else
<else block>
Then BlockThen Block
Else BlockElse Block
Boolean ExpressionBoolean Expression
2005 Pearson Education, Inc. All rights reserved.
15
Outline• Comparison.java
• (1 of 2)
1 // Fig. 2.15: Comparison.java 2 // Compare integers using if statements, relational operators 3 // and equality operators. 4 import java.util.Scanner; // program uses class Scanner 5 6 public class Comparison 7 { 8 // main method begins execution of Java application 9 public static void main( String args[] ) 10 { 11 // create Scanner to obtain input from command window 12 Scanner input; Input = new Scanner( System.in ); 13 14 int number1; // first number to compare 15 int number2; // second number to compare 16 17 System.out.print( "Enter first integer: " ); // prompt 18 number1 = input.nextInt(); // read first number from user 19 20 System.out.print( "Enter second integer: " ); // prompt 21 number2 = input.nextInt(); // read second number from user 22 23 if ( number1 == number2 ) 24 System.out.print( number1 + " Equal " + number2 + “\n” ); 25 26 if ( number1 != number2 ) 27 System.out.printf( "%d != %d\n", number1, number2 ); 28 29 if ( number1 < number2 ) 30 System.out.printf( "%d < %d\n", number1, number2 );
Test for equality, display result using printf.
Compares two numbers using relational operator <.
2005 Pearson Education, Inc. All rights reserved.
16
Outline
• Comparison.java
• (2 of 2)
• Program output
31 32 if ( number1 > number2 ) 33 System.out.printf( "%d > %d\n", number1, number2 );
34
35 if ( number1 <= number2 )
36 System.out.printf( "%d <= %d\n", number1, number2 );
37
38 if ( number1 >= number2 )
39 System.out.printf( "%d >= %d\n", number1, number2 );
40
41 } // end method main
42
43 } // end class Comparison Enter first integer: 777 Enter second integer: 777 777 == 777 777 <= 777 777 >= 777 Enter first integer: 1000 Enter second integer: 2000 1000 != 2000 1000 < 2000 1000 <= 2000
Enter first integer: 2000 Enter second integer: 1000 2000 != 1000 2000 > 1000 2000 >= 1000
Compares two numbers using relational operator >, <= and >=.
2005 Pearson Education, Inc. All rights reserved.
17
Common Programming Error 9
• Placing a semicolon immediately after the right parenthesis of the condition in an if statement is normally a logic error.
2005 Pearson Education, Inc. All rights reserved.
18
Decision Making: Equality and Relational Operators (Cont.)
– Line 6: begins class Comparison declaration
– Line 12: declares Scanner variable input and assigns it a Scanner that inputs data from the standard input
– Lines 14-15: declare int variables
– Lines 17-18: prompt the user to enter the first integer and input the value
– Lines 20-21: prompt the user to enter the second integer and input the value
1 // Fig. 2.15: Comparison.java 2 // Compare integers using if statements, relational operators 3 // and equality operators. 4 import java.util.Scanner; // program uses class Scanner 5 6 public class Comparison 7 { 8 // main method begins execution of Java application 9 public static void main( String args[] ) 10 { 11 // create Scanner to obtain input from command window 12 Scanner input = new Scanner( System.in ); 13 14 int number1; // first number to compare 15 int number2; // second number to compare 16 17 System.out.print( "Enter first integer: " ); // prompt 18 number1 = input.nextInt(); // read first number from user 19 20 System.out.print( "Enter second integer: " ); // prompt 21 number2 = input.nextInt(); // read second number from user 22 23 if ( number1 == number2 ) 24 System.out.printf( "%d == %d\n", number1, number2 ); 25 26 if ( number1 != number2 ) 27 System.out.printf( "%d != %d\n", number1, number2 ); 28 29 if ( number1 < number2 ) 30 System.out.printf( "%d < %d\n", number1, number2 );
2005 Pearson Education, Inc. All rights reserved.
19
Decision Making: Equality and Relational Operators (Cont.)
– if statement to test for equality using (==)• If variables equal (condition true)
– Line 24 executes
• If variables not equal, statement skipped
• No semicolon at the end of if statement
• Empty statement– No task is performed
– Lines 26-27, 29-30, 32-33, 35-36 and 38-39• Compare number1 and number2 with the operators !=, <, >, <= and >=, respectively
23 if ( number1 == number2 )
24 System.out.printf( "%d == %d\n", number1, number2 );
2005 Pearson Education, Inc. All rights reserved.
20
Common Programming Error 10
• Confusing the equality operator, ==, with the assignment operator, =, can cause a logic error or a syntax error.
• The equality operator should be read as “is equal to,” and the assignment operator should be read as “gets” or “gets the value of.” To avoid confusion, some people read the equality operator as “double equals” or “equals equals.”
2005 Pearson Education, Inc. All rights reserved.
21
Common Programming Error 11
• It is a syntax error if the operators ==, !=, >= and <= contain spaces between their symbols, as in = =, ! =, > = and < =, respectively.
Common Programming Error 12
• Reversing the operators !=, >= and <=, as in =!, => and =<, is a syntax error.
2005 Pearson Education, Inc. All rights reserved.
22
Good Programming Practice 8
• A lengthy statement can be spread over several lines. If a single statement must be split across lines, choose breaking points that make sense, such as after a comma in a comma-separated list, or after an operator in a lengthy expression. If a statement is split across two or more lines, indent all subsequent lines until the end of the statement.
2005 Pearson Education, Inc. All rights reserved.
23
Good Programming Practice 8
• Refer to the operator precedence chart (see the complete chart in Appendix A) when writing expressions containing many operators. Confirm that the operations in the expression are performed in the order you expect. If you are uncertain about the order of evaluation in a complex expression, use parentheses to force the order, exactly as you would do in algebraic expressions. Observe that some operators, such as assignment, =, associate from right to left rather than from left to right.
2005 Pearson Education, Inc. All rights reserved.
24
Fig. 2.16 | Precedence and associativity of operations discussed.
Operators Associativity Type
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
= right to left assignment
2005 Pearson Education, Inc. All rights reserved.
25
if (testScore < 70)
{
JOptionPane.showMessageDialog(null, "You did not pass“ );
JOptionPane.showMessageDialog(null, “Try harder next time“ );
}
else
{
JOptionPane.showMessageDialog(null, “You did pass“ );
JOptionPane.showMessageDialog(null, “Keep up the good work“ );
}
Compound Statements• Use braces if the <then> or <else> block has multiple statements.
Then BlockThen Block
Else BlockElse Block
2005 Pearson Education, Inc. All rights reserved.
26
if ( <boolean expression> ) {
…
}
else {
…
}
Style Guide
if ( <boolean expression> )
{
…
}
else
{
…
}
Style 1Style 1
Style 2Style 2
2005 Pearson Education, Inc. All rights reserved.
27
The if-then Statementif ( <boolean expression> )
<then block>
if ( testScore >= 95 )
JOptionPane.showMessageDialog(null,"You are an honor student");Then BlockThen Block
Boolean ExpressionBoolean Expression
2005 Pearson Education, Inc. All rights reserved.
28
Control Flow of if-then
testScore >= 95?
testScore >= 95?
falseJOptionPane.showMessageDialog (null, "You are an honor student");
JOptionPane.showMessageDialog (null, "You are an honor student");
true
2005 Pearson Education, Inc. All rights reserved.
29
The Nested-if Statement
• The then and else block of an if statement can contain any valid statements, including other if statements. An if statement containing another if statement is called a nested-if statement.
if (testScore >= 70) {
if (studentAge < 10) {
System.out.println("You did a great job");
} else {
System.out.println("You did pass"); //test score >= 70
} //and age >= 10
} else { //test score < 70
System.out.println("You did not pass");
}
2005 Pearson Education, Inc. All rights reserved.
30
Control Flow of Nested-if Statement
messageBox.show("You did not pass");
messageBox.show("You did not pass");
false inner if
messageBox.show("You did pass");
messageBox.show("You did pass");
false
testScore >= 70 ?
testScore >= 70 ?
true
studentAge < 10 ?
studentAge < 10 ?
messageBox.show("You did a great job");
messageBox.show("You did a great job");
true
2005 Pearson Education, Inc. All rights reserved.
31
Writing a Proper if Controlif (num1 < 0)
if (num2 < 0)
if (num3 < 0)
negativeCount = 3;
else
negativeCount = 2;
else
if (num3 < 0)
negativeCount = 2;
else
negativeCount = 1;
else
if (num2 < 0)
if (num3 < 0)
negativeCount = 2;
else
negativeCount = 1;
else
if (num3 < 0)
negativeCount = 1;
else
negativeCount = 0;
negativeCount = 0;
if (num1 < 0)
negativeCount++;
if (num2 < 0)
negativeCount++;
if (num3 < 0)
negativeCount++;
The statement
negativeCount++;
increments the variable by one
The statement
negativeCount++;
increments the variable by one
What is the values of negativeCount when executing the fragment code shown and num1, num2, and num3 values as shown
num1 = -2, num2 = -2, num3 = 2
num1 = 2, num2 = -2, num3 = 2
num1 = -2, num2 = -2, num3 =-2
num1 = 2, num2 = 2, num3 = -2
num1 = -2, num2 = -2, num3 = 2
2005 Pearson Education, Inc. All rights reserved.
32
if – else if Control
if (score >= 90)
System.out.print("Your grade is A");
else if (score >= 80)
System.out.print("Your grade is B");
else if (score >= 70)
System.out.print("Your grade is C");
else if (score >= 60)
System.out.print("Your grade is D");
else
System.out.print("Your grade is F");
Test Score Grade90 score A
80 score 90
B
70 score 80
C
60 score 70
D
score 60 F
2005 Pearson Education, Inc. All rights reserved.
33
Matching else
if (x < y)
if (x < z)
System.out.print("Hello");
else
System.out.print("Good bye");
AA
if (x < y)
if (x < z)
System.out.print("Hello");
else
System.out.print("Good bye");
BB
Are and different?AA BB
if (x < y) {
if (x < z) {
System.out.print("Hello");
} else {
System.out.print("Good bye");
}
}
Both and means…AA BB
2005 Pearson Education, Inc. All rights reserved.
34
5.1 Introduction
Introduce Java’s remaining control structures
for, while , do…while
2005 Pearson Education, Inc. All rights reserved.
35
Fig. 5.3 | for statement header components.
2005 Pearson Education, Inc. All rights reserved.
36
Outline
1 // Fig. 5.2: ForCounter.java
2 // Counter-controlled repetition with the for repetition statement.
3
4 public class ForCounter
5 {
6 public static void main( String args[] )
7 {
8 // for statement header includes initialization,
9 // loop-continuation condition and increment
10 for ( int counter = 1; counter <= 10; counter++ )
11 System.out.printf( "%d ", counter );
12
13 System.out.println(); // output a newline
14 } // end main
15 } // end class ForCounter 1 2 3 4 5 6 7 8 9 10
Control-variable name is counter
Control-variable initial value is 1
Condition tests for counter’s final value
Increment for counter
2005 Pearson Education, Inc. All rights reserved.
37
for Repetition Statement (Cont.)
for ( initialization; loopContinuationCondition; increment ) for ( initialization; loopContinuationCondition; increment )
statement;statement;
can usually be rewritten as:can usually be rewritten as:
initialization;initialization;while ( loopContinuationCondition ) while ( loopContinuationCondition )
{{ statement; statement; increment; increment;}}
2005 Pearson Education, Inc. All rights reserved.
38
Error-Prevention Tip
Although the value of the control variable can be changed in the body of a for loop, avoid doing so, because this practice can lead to subtle errors.
2005 Pearson Education, Inc. All rights reserved.
39
Fig. 5.4 | UML activity diagram for the for statement in Fig. 5.2.
for ( int counter = 1; counter <= 10; counter++ )
System.out.printf( "%d ", counter );
2005 Pearson Education, Inc. All rights reserved.
40
Examples Using the for Statement
Varying control variable in for statementVary control variable from 1 to 100 in increments of 1
for ( int i = 1; i <= 100; i++ )Vary co ntrol variable from 100 to 1 in increments of –1
for ( int i = 100; i >= 1; i-- )Vary control variable from 7 to 77 in increments of 7
for ( int i = 7; i <= 77; i += 7 )Vary control variable from 20 to 2 in decrements of 2
for ( int i = 20; i >= 2; i -= 2 )Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20
for ( int i = 2; i <= 20; i += 3 )Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0
for ( int i = 99; i >= 0; i -= 11 )
2005 Pearson Education, Inc. All rights reserved.
41
Outline
Sum.java
Line 11
1 // Fig. 5.5: Sum.java
2 // Summing integers with the for statement.
3
4 public class Sum
5 {
6 public static void main( String args[] )
7 {
8 int total = 0; // initialize total
9
10 // total even integers from 2 through 20
11 for ( int number = 2; number <= 20; number += 2 )
12 total += number;
13
14 System.out.printf( "Sum is %d\n", total ); // display results
15 } // end main
16 } // end class Sum Sum is 110
increment number by 2 each iteration
2005 Pearson Education, Inc. All rights reserved.
42
Examples Using the for Statement (Cont.)
Initialization and increment expression can be comma-separated lists of expressions
11 for ( int number = 2; number <= 20; number += 2 )
12 total += number; E.g., lines 11-12 of Fig. 5.5 can be rewritten as
for ( int number = 2; number <= 20; total += number, number += 2 )
; // empty statement
2005 Pearson Education, Inc. All rights reserved.
43
Outline
1 // Fig. 5.6: Interest.java
2 // Compound-interest calculations with for.
3
4 public class Interest
5 {
6 public static void main( String args[] )
7 {
8 double amount; // amount on deposit at end of each year
9 double principal = 1000.0; // initial amount before interest
10 double rate = 0.05; // interest rate
11
12 // display headers
13 System.out.printf( "%s%20s\n", "Year", "Amount on deposit" );
14
Java treats floating-points as type double
Second string is right justified and displayed with a field width of 20
2005 Pearson Education, Inc. All rights reserved.
44
Outline
15 // calculate amount on deposit for each of ten years
16 for ( int year = 1; year <= 10; year++ )
17 {
18 // calculate new amount for specified year
19 amount = principal * Math.pow( 1.0 + rate, year );
20
21 // display the year and the amount
22 System.out.printf( "%4d%,20.2f\n", year, amount );
23 } // end for
24 } // end main
25 } // end class Interest Year Amount on deposit 1 1,050.00 2 1,102.50 3 1,157.63 4 1,215.51 5 1,276.28 6 1,340.10 7 1,407.10 8 1,477.46 9 1,551.33 10 1,628.89
Calculate amount with for statement
Use the comma (,) formatting flag to display the amount with a thousands separator
2005 Pearson Education, Inc. All rights reserved.
45
Increment and Decrement Operators
Unary increment and decrement operators
Unary increment operator (++) adds one to its operand
Unary decrement operator (--) subtracts one from its operand
Prefix increment (and decrement) operator
Changes the value of its operand, then uses the new value of the operand in the expression in which the operation appears
Postfix increment (and decrement) operator
Uses the current value of its operand in the expression in which the operation appears, then changes the value of the operand
2005 Pearson Education, Inc. All rights reserved.
46
Fig. 4.15 | Increment and decrement operators.
Operator Called Sample expression
Explanation
++ prefix increment ++a Increment a by 1, then use the new value of a in the
expression in which a resides.
++ postfix increment
a++ Use the current value of a in the expression in which a resides, then increment a by 1.
-- prefix decrement
--b Decrement b by 1, then use the new value of b in the expression in which b resides.
-- postfix decrement
b-- Use the current value of b in the expression in which b resides, then decrement b by 1.
2005 Pearson Education, Inc. All rights reserved.
47
Outline
Increment.java
1 // Fig. 4.16: Increment.java 2 // Prefix increment and postfix increment operators. 3
4 public class Increment 5 { 6 public static void main( String args[] ) 7 { 8 int c; 9
10 // demonstrate postfix increment operator 11 c = 5; // assign 5 to c 12 System.out.println( c ); // print 5
13 System.out.println( c++ ); // print 5 then postincrement 14 System.out.println( c ); // print 6 15
16 System.out.println(); // skip a line 17
18 // demonstrate prefix increment operator 19 c = 5; // assign 5 to c 20 System.out.println( c ); // print 5 21 System.out.println( ++c ); // preincrement then print 6 22 System.out.println( c ); // print 6 23
24 } // end main 25
26 } // end class Increment
5 5 6 5 6 6
Postincrementing the c variable
Preincrementing the c variable
2005 Pearson Education, Inc. All rights reserved.
48
4.11 Compound Assignment Operators
Compound assignment operators
An assignment statement of the form:variable = variable operator expression;
where operator is +, -, *, / or % can be written as:variable operator= expression;
example: c = c + 3; can be written as c += 3;
This statement adds 3 to the value in variable c and stores the result in variable c
2005 Pearson Education, Inc. All rights reserved.
49
Fig. 4.14 | Arithmetic compound assignment operators.
Assignment operator
Sample expression
Explanation Assigns
Assume: int c = 3, d = 5, e = 4, f = 6, g = 12; += c += 7 C = c + 7 10 to c -= d -= 4 d = d - 4 1 to d *= e *= 5 e = e * 5 20 to e /= f /= 3 f = f / 3 2 to f
%= g %= 9 g = g % 9 3 to g
2005 Pearson Education, Inc. All rights reserved.
50
Common Programming Error 4.9
Attempting to use the increment or decrement operator on an expression other than one to which a value can be assigned is a syntax error.
For example, writing ++(x + 1) is a syntax error because (x + 1) is not a variable.
2005 Pearson Education, Inc. All rights reserved.
51
Fig. 4.17 | Precedence and associativity of the operators discussed so far.
Operators Associativity Type ++ -- right to left unary postfix
++ -- + - ( type ) right to left unary prefix * / % left to right Multiplicative + - left to right Additive < <= > >= left to right Relational == != left to right Equality ?: right to left Conditional
= += -= *= /= %= right to left assignment
2005 Pearson Education, Inc. All rights reserved.
52
while Repetition Statement
• while statement
–Repeats an action while its loop-continuation condition remains true
2005 Pearson Education, Inc. All rights reserved.
53
for Repetition Statement (Cont.)
for ( initialization; loopContinuationCondition; increment ) for ( initialization; loopContinuationCondition; increment )
statement;statement;
can usually be rewritten as:can usually be rewritten as:
initialization;initialization;while ( loopContinuationCondition ) while ( loopContinuationCondition )
{{ statement; statement; increment; increment;}}
2005 Pearson Education, Inc. All rights reserved.
54
Outline
WhileCounter.java
1 // Fig. 5.1: WhileCounter.java
2 // Counter-controlled repetition with the while repetition statement.
3
4 public class WhileCounter
5 {
6 public static void main( String args[] )
7 {
8 int counter = 1; // declare and initialize control variable
9
10 while ( counter <= 10 ) // loop-continuation condition
11 {
12 System.out.printf( "%d ", counter );
13 ++counter; // increment control variable by 1
14 } // end while
15
16 System.out.println(); // output a newline
17 } // end main
18 } // end class WhileCounter 1 2 3 4 5 6 7 8 9 10
Control-variable name is counter
Control-variable initial value is 1Condition tests for counter’s
final value
Increment for counter
2005 Pearson Education, Inc. All rights reserved.
55Calculate.java// Calculate the sum of the integers from 1 to 10
public class Calculate { public static void main( String args[] ) { int sum; int x;
x = 1; // initialize x to 1 for counting sum = 0; // initialize sum to 0 for totaling
while ( x <= 10 ) // while x is less than or equal to 10 { sum += x; // add x to sum sum = sum + x; ++x; // increment x } // end while
System.out.printf( "The sum is: %d\n", sum ); } // end main
} // end class Calculate
2005 Pearson Education, Inc. All rights reserved.
56
Mystery.java
Q : What is this program calculate f(x) ?
public class Mystery { public static void main( String args[] ) { int y; int x = 1; int total = 0;
while ( x <= 10 ) { y = x * x; System.out.println( y ); total += y; ++x; } // end while
System.out.printf( "Total is %d\n", total ); } // end main
} // end class Mystery
/**************************************************************
2005 Pearson Education, Inc. All rights reserved.
57
Fig. 4.4 | while repetition statement UML activity diagram.
Diamonds
Decision symbols (explained in section 4.5)
Merge symbols (explained in section 4.7) int product = 3;
while (product <= 100)
product = 3 * product
2005 Pearson Education, Inc. All rights reserved.
58
Fig. 4.5 | Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem.
1 Set total to zero
2 Set grade counter to one
3
4 While grade counter is less than or equal to ten
5 Prompt the user to enter the next grade
6 Input the next grade
7 Add the grade into the total
8 Add one to the grade counter
9
10 Set the class average to the total divided by ten
11 Print the class average
2005 Pearson Education, Inc. All rights reserved.
59
class GradeBook { // display a welcome message to the GradeBook user
public void displayMessage() {
// getCourseName gets the name of the course
System.out.printf( "Welcome to the grade book\n for \n CSC111 \n!\n\n" );
} // end method displayMessage
} // end class GradeBook
2005 Pearson Education, Inc. All rights reserved.
60
// GradeBookTestExample2.java
import java.util.Scanner; // program uses class Scanner
public class GradeBookTestExample2{ public static void main( String args[] ) {
// determine class average based on 10 grades entered by user
int total; // sum of grades entered by user
int gradeCounter; // number of the grade to be entered next
int grade; // grade value entered by user
int average; // average of grades
// create GradeBook object myGradeBook
GradeBook myGradeBook = new GradeBook(); myGradeBook.displayMessage(); // display welcome message
2005 Pearson Education, Inc. All rights reserved.
61
// find average of 10 grades
// create Scanner to obtain input from command window Scanner input = new Scanner( System.in );
// initialization phase total = 0; // initialize total gradeCounter = 1; // initialize loop counter // processing phase while ( gradeCounter <= 10 ) // loop 10 times { System.out.print( "Enter grade: " ); // prompt grade = input.nextInt(); // read grade from user total = total + grade; // add grade to total gradeCounter = gradeCounter + 1; // increment counter by 1 } // end while
2005 Pearson Education, Inc. All rights reserved.
62
// termination phase average = total / 10; // integer division yields integer result
// display total and average of grades System.out.printf( "\nTotal of all 10 grades is %d\n", total ); System.out.printf( "Class average is %d\n", average );
} // end main
} // end class GradeBookTestExample2
2005 Pearson Education, Inc. All rights reserved.
63
// Analysis of examination results.import java.util.Scanner; // class uses class Scanner
public class AnalysisTestExample1 { public static void main( String args[] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in );
// initializing variables in declarations int passes = 0; // number of passes int failures = 0; // number of failures int studentCounter = 1; // student counter int result; // one exam result (obtains value from user)
2005 Pearson Education, Inc. All rights reserved.
64
// process 10 students using counter-controlled loop
while ( studentCounter <= 10 ) { // prompt user for input and obtain value from user System.out.print( "Enter result from 00: 100" ); result = input.nextInt();
// if...else nested in while if ( result >= 60 ) // if result >=60, passes = passes + 1; // increment passes; else // else result is < 60, so failures = failures + 1; // increment failures
// increment studentCounter so loop eventually terminates studentCounter = studentCounter + 1;
} // end while
2005 Pearson Education, Inc. All rights reserved.
65
// termination phase; prepare and display results
System.out.printf( "Passed: %d\nFailed: %d\n", passes, failures );
// determine whether more than 8 students passed
if ( passes > 8 ) System.out.println( "Raise Tuition" );
} // end main
} // end class AnalysisTest1
2005 Pearson Education, Inc. All rights reserved.
Defining Your Own Classes and Methods
2005 Pearson Education, Inc. All rights reserved.
67
Standard Input
The technique of using System.in to input data is called standard input.
We can only input a single byte using System.in directly.
To input primitive data values, we use the Scanner class
(from Java 5.0).
Scanner scanner;
scanner = Scanner.create(System.in);
int num = scanner.nextInt();
Standard InputStandard Input
2005 Pearson Education, Inc. All rights reserved.
68
Method Example
nextByte( ) byte b = scanner.nextByte( );
nextDouble( ) double d = scanner.nextDouble( );
nextFloat( ) float f = scanner.nextFloat( );
nextInt( ) int i = scanner.nextInt( );
nextLong( ) long l = scanner.nextLong( );
nextShort( ) short s = scanner.nextShort( );
next() String str = scanner.next();
Common Scanner Methods:
2005 Pearson Education, Inc. All rights reserved.
69
A class
• A class is the blueprint from which objects are generated. In other words, if we have six cars we do not need to define a car six times. We will define a car once (in a class) and then generate as many objects as we want from this class blueprint.
2005 Pearson Education, Inc. All rights reserved.
2005 Pearson Education, Inc. All rights reserved.
UML representationUML representation
2005 Pearson Education, Inc. All rights reserved.
2005 Pearson Education, Inc. All rights reserved.
2005 Pearson Education, Inc. All rights reserved.
2005 Pearson Education, Inc. All rights reserved.
Sending a Message
myWindow . setVisible ( true ) ;
MoreExamples
account.deposit( 200.0 );student.setName(“john”);car1.startEngine( );
Object NameName of the object to which we are sending a message.
Object NameName of the object to which we are sending a message.
Method NameThe name of the message we are sending.
Method NameThe name of the message we are sending.
ArgumentThe argument we are passing with the message.
ArgumentThe argument we are passing with the message.
2005 Pearson Education, Inc. All rights reserved.
Execution Flow
myWindow.width = 300;
Jframe myWindow;
myWindow
myWindow.visible = true;
State-of-Memory Diagram
: JFrame
width
height
title
visible
200
My First Java …
300
true
myWindow = new JFrame( );
myWindow.title = “My First Java Program”;
The diagram shows only four of the many data members of a JFrame object.
The diagram shows only four of the many data members of a JFrame object.
Program Code
myWindow.height = 200;
2005 Pearson Education, Inc. All rights reserved.
JFrame myWindow;
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle (“My First Java Program”);
myWindow.setVisible(true);
Execution Flow
myWindow.setSize(300, 200);
Jframe myWindow;
myWindow
myWindow.setVisible(true);
State-of-Memory Diagram
: JFrame
width
height
title
visible
200
My First Java …
300
true
myWindow = new JFrame( );
myWindow.setTitle (“My First Java Program”);
The diagram shows only four of the many data members of a JFrame object.
The diagram shows only four of the many data members of a JFrame object.
Program Code
The effect of the setSize method is changing the value of width and height.
The effect of the setTitle method is changing the title string to the passed argument.
And the effect of setVisible is the changing the value of visible to true, and as a result,
the appearance of the window on the screen.
2005 Pearson Education, Inc. All rights reserved.
78
Standard Input
The technique of using System.in to input data is called standard input.
We can only input a single byte using System.in directly.
To input primitive data values, we use the Scanner class
(from Java 5.0).
Scanner scanner;
scanner = Scanner.create(System.in);
int num = scanner.nextInt();
Standard InputStandard Input
2005 Pearson Education, Inc. All rights reserved.
The Definition of the Bicycle Class
class Bicycle {
// Data Member public String ownerName;
public float price ;public int size ;
}
2005 Pearson Education, Inc. All rights reserved.
Multiple Instances
• Once the Bicycle class is defined, we can create multiple instances. Notice how all the instances have their own copy of data members.
Bicycle bike1, bike2;
bike1 bike2
: Bicycle
ownerName
: Bicycle
ownerName
“Adam Smith” “Ben Jones”
bike1 = new Bicycle( ); bike1.ownerName = "Adam Smith";
bike2 = new Bicycle( );
bike2.ownerName = "Ben Jones";
Sample Code
2005 Pearson Education, Inc. All rights reserved.
First Example: Using the Bicycle Class
import java.util.Scanner; // class uses class Scanner
class BicycleRegistration {
public static void main(String[] args) {
Bicycle bike1, bike2;
String owner1, owner2;
float price1, price2;
int size1, size2;
// create Scanner to obtain input from command window Scanner input = new Scanner( System.in );
bike1 = new Bicycle( ); //Create and assign values to bike1
// prompt user for input and obtain value from user System.out.print( "Enter the owner name" );
bike1.ownerName = input.next();
owner1 = bike1.ownerName;
bike2 = new Bicycle( ); //Create and assign values to bike2
// prompt user for input and obtain value from user System.out.print( "Enter the owner name" );
bike2.ownerName = input.next();
owner2 = bike2.ownerName;
This sample program shows the main class BicycleRegistration is using the Bicycle class. .
bike1.ownerName = "Adam Smith";
bike2.ownerName = "Ben Jones";
2005 Pearson Education, Inc. All rights reserved.
The Definition of the Bicycle Class
// prompt user for input and obtain value from user System.out.print( "Enter the Price of Bike 1" );
bike1.price = input.nextFloat();
price1 = bike1.price;
// prompt user for input and obtain value from user System.out.print( "Enter the Size of Bike 1" );
bike1.size = input.nextInt();
size1 = bike1.size;
…
System.out.println(owner1 + " owns a bicycle Its price is“
+ bike1.price + “ Its size is “ + bike1.size);
System.out.println(owner2 + " also owns a bicycle.");
}
}
2005 Pearson Education, Inc. All rights reserved.
UML representationUML representation
2005 Pearson Education, Inc. All rights reserved.
2005 Pearson Education, Inc. All rights reserved.
The Program Structure and Source Files
BicycleRegistration Bicycle
There are two source files. Each class definition is stored in a separate file.
There are two source files. Each class definition is stored in a separate file.
BicycleRegistration.java Bicycle.java
To run the program: 1. javac Bicycle.java (compile)
2. javac BicycleRegistration.java (compile)
3. java BicycleRegistration (run)
2005 Pearson Education, Inc. All rights reserved.
86
switch Multiple-Selection Statement
switch statementUsed for multiple selections
2005 Pearson Education, Inc. All rights reserved.
87
switchswitch multiple-selection statement UML activity diagram multiple-selection statement UML activity diagram
with with breakbreak statements statements.
2005 Pearson Education, Inc. All rights reserved.
88
OutlineGradeBook5.java(1 of 5)
2005 Pearson Education, Inc. All rights reserved.
89
GradeBook5.java
(2 of 5)
Display prompt
Loop condition uses grade to determine whether there is more data to input
2005 Pearson Education, Inc. All rights reserved.
90GradeBook.java
(3 of 5)
(grade / 10 ) is controlling expression
switch statement determines which case label to execute, depending on
controlling expression
default case for grade less than 60
2005 Pearson Education, Inc. All rights reserved.
91
OutlineGradeBook.java
(4 of 5)
Line 91 default case
2005 Pearson Education, Inc. All rights reserved.
92
Common Programming Error
Forgetting a break statement when one is needed in a switch is a logic error.
2005 Pearson Education, Inc. All rights reserved.
93
OutlineGradeBookTest.java
(1 of 2)
Call GradeBook public methods to count grades
2005 Pearson Education, Inc. All rights reserved.
94
OutlineGradeBookTest.java
(2 of 2)
Program output
2005 Pearson Education, Inc. All rights reserved.
95
Good Programming Practice
Although each case and the default case in a switch can occur in any order, place the default case last. When the default case is listed last, the break for that case is not required. Some programmers include this break for clarity and symmetry with other cases.
2005 Pearson Education, Inc. All rights reserved.
96
switch Multiple-Selection Statement (Cont.)
• Expression in each case– Constant integral expression
• Combination of integer constants that evaluates to a constant integer value
– Character constant• E.g., ‘A’, ‘7’ or ‘$’
– Constant variable• Declared with keyword final
2005 Pearson Education, Inc. All rights reserved.
97
switch Multiple-Selection Statement (Cont.)
• Expression in each case– Constant integral expression
• Combination of integer constants that evaluates to a constant integer value
– Character constant• E.g., ‘A’, ‘7’ or ‘$’
– Constant variable• Declared with keyword final
2005 Pearson Education, Inc. All rights reserved.
98
break and continue Statements
•break/continue– Alter flow of control
•break statement – Causes immediate exit from control structure
• Used in while, for, do…while or switch statements
•continue statement – Skips remaining statements in loop body
– Proceeds to next iteration• Used in while, for or do…while statements
2005 Pearson Education, Inc. All rights reserved.
99
Outline 1 // Fig. 5.12: BreakTest.java 2 // break statement exiting a for statement. 3 public class BreakTest 4 { 5 public static void main( String args[] ) 6 { 7 int count; // control variable also used after loop terminates 8 9 for ( count = 1; count <= 10; count++ ) // loop 10 times 10 { 11 if ( count == 5 ) // if count is 5, 12 break; // terminate loop 13 14 System.out.printf( "%d ", count ); 15 } // end for 16 17 System.out.printf( "\nBroke out of loop at count = %d\n", count ); 18 } // end main 19 } // end class BreakTest
1 2 3 4 Broke out of loop at count = 5
Loop 10 times
Exit for statement (break) when count equals 5
2005 Pearson Education, Inc. All rights reserved.
1 // Fig. 5.13: ContinueTest.java
2 // continue statement terminating an iteration of a for statement.
3 public class ContinueTest
4 {
5 public static void main( String args[] )
6 {
7 for ( int count = 1; count <= 10; count++ ) // loop 10 times
8 {
9 if ( count == 5 ) // if count is 5,
10 continue; // skip remaining code in loop
11
12 System.out.printf( "%d ", count );
13 } // end for
14
15 System.out.println( "\nUsed continue to skip printing 5" );
16 } // end main
17 } // end class ContinueTest 1 2 3 4 6 7 8 9 10 Used continue to skip printing 5
Loop 10 times
Skip line 12 and proceed to line 7 when count equals 5
2005 Pearson Education, Inc. All rights reserved.
101
Boolean Operators
• A boolean operator takes boolean values as its operands and returns a boolean value.
• The three boolean operators are– and: &&
– or: ||
– not !
if (temperature >= 65 && distanceToDestination < 2) {System.out.println("Let's walk");
} else {System.out.println("Let's drive");
}
2005 Pearson Education, Inc. All rights reserved.
102
Logical Operators
• Logical operators– Allows for forming more complex conditions
– Combines simple conditions
• Java logical operators– && (conditional AND)
– || (conditional OR)
– & (boolean logical AND)
– | (boolean logical inclusive OR)
– ^ (boolean logical exclusive OR)
– ! (logical NOT)
2005 Pearson Education, Inc. All rights reserved.
103
Logical Operators (Cont.)
• Conditional AND (&&) Operator– Consider the following if statement
if ( gender == FEMALE && age >= 65 )
++seniorFemales;
– Combined condition is true • if and only if both simple conditions are true
– Combined condition is false • if either or both of the simple conditions are false
2005 Pearson Education, Inc. All rights reserved.
104
&& (conditional AND) operator truth table.
expression1 expression2 expression1 && expression2 false false False false true False true false False true true True
2005 Pearson Education, Inc. All rights reserved.
105
Logical Operators (Cont.)
• Conditional OR (||) Operator– Consider the following if statement– if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 )
System.out.println( “Student grade is A” );
– Combined condition is true • if either or both of the simple condition are true
– Combined condition is false • if both of the simple conditions are false
2005 Pearson Education, Inc. All rights reserved.
106
|| (conditional OR) operator truth table.
expression1 expression2 expression1 || expression2 false false false false true true true false true true true true
2005 Pearson Education, Inc. All rights reserved.
107
Logical Operators (Cont.)
• Short-Circuit Evaluation of Complex Conditions– Parts of an expression containing && or || operators are
evaluated only until it is known whether the condition is true or false
– E.g., ( gender == FEMALE ) && ( age >= 65 )• Stops immediately if gender is not equal to FEMALE
2005 Pearson Education, Inc. All rights reserved.
108
Common Programming Error
• For example, in the expression
( i != 0 ) && ( 10 / i == 2 ) , the second condition must appear after the first condition, or a divide-by-zero error might occur.
2005 Pearson Education, Inc. All rights reserved.
109
Logical Operators (Cont.)
• Boolean Logical AND (&) Operator– Works identically to &&
– Except & always evaluate both operands
• Boolean Logical OR (|) Operator – Works identidally to ||
– Except | always evaluate both operands
2005 Pearson Education, Inc. All rights reserved.
110
Logical Operators (Cont.)
• Boolean Logical Exclusive OR (^)– One of its operands is true and the other is false
• Evaluates to true
– Both operands are true or both are false• Evaluates to false
• Logical Negation (!) Operator– Unary operator
2005 Pearson Education, Inc. All rights reserved.
111
^ (boolean logical exclusive OR) operator truth table.
expression1 expression2 expression1 ^ expression2 false false false false true true true false true true true false
2005 Pearson Education, Inc. All rights reserved.
112
! (logical negation, or logical NOT) operator truth table.
expression !expression false true true false
2005 Pearson Education, Inc. All rights reserved.
113
Outline 1 // Fig. 5.18: LogicalOperators.java
2 // Logical operators.
3
4 public class LogicalOperators
5 {
6 public static void main( String args[] )
7 {
8 // create truth table for && (conditional AND) operator
9 System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n",
10 "Conditional AND (&&)", "false && false", ( false && false ),
11 "false && true", ( false && true ),
12 "true && false", ( true && false ),
13 "true && true", ( true && true ) );
14
15 // create truth table for || (conditional OR) operator
16 System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n",
17 "Conditional OR (||)", "false || false", ( false || false ),
18 "false || true", ( false || true ),
19 "true || false", ( true || false ),
20 "true || true", ( true || true ) );
21
22 // create truth table for & (boolean logical AND) operator
23 System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n",
24 "Boolean logical AND (&)", "false & false", ( false & false ),
25 "false & true", ( false & true ),
26 "true & false", ( true & false ),
27 "true & true", ( true & true ) );
28
Conditional AND truth table
Conditional OR truth table
Boolean logical AND truth table
2005 Pearson Education, Inc. All rights reserved.
114
Outline29 // create truth table for | (boolean logical inclusive OR) operator
30 System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n",
31 "Boolean logical inclusive OR (|)",
32 "false | false", ( false | false ),
33 "false | true", ( false | true ),
34 "true | false", ( true | false ),
35 "true | true", ( true | true ) );
36
37 // create truth table for ^ (boolean logical exclusive OR) operator
38 System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n",
39 "Boolean logical exclusive OR (^)",
40 "false ^ false", ( false ^ false ),
41 "false ^ true", ( false ^ true ),
42 "true ^ false", ( true ^ false ),
43 "true ^ true", ( true ^ true ) );
44
45 // create truth table for ! (logical negation) operator
46 System.out.printf( "%s\n%s: %b\n%s: %b\n", "Logical NOT (!)",
47 "!false", ( !false ), "!true", ( !true ) );
48 } // end main
49 } // end class LogicalOperators
Boolean logical inclusive OR truth table
Boolean logical exclusive OR truth table
Logical negation truth table
2005 Pearson Education, Inc. All rights reserved.
115
Outline Conditional AND (&&) false && false: false false && true: false true && false: false true && true: true Conditional OR (||) false || false: false false || true: true true || false: true true || true: true Boolean logical AND (&) false & false: false false & true: false true & false: false true & true: true Boolean logical inclusive OR (|) false | false: false false | true: true true | false: true true | true: true Boolean logical exclusive OR (^) false ^ false: false false ^ true: true true ^ false: true true ^ true: false Logical NOT (!) !false: true !true: false
2005 Pearson Education, Inc. All rights reserved.
Mid Term Exam
116
2005 Pearson Education, Inc. All rights reserved.
117
Examples
2005 Pearson Education, Inc. All rights reserved.
118
2005 Pearson Education, Inc. All rights reserved.
119
2005 Pearson Education, Inc. All rights reserved.
120
2005 Pearson Education, Inc. All rights reserved.
121
1 from 3
2005 Pearson Education, Inc. All rights reserved.
122
2 from 3
2005 Pearson Education, Inc. All rights reserved.
123
3 from 3
2005 Pearson Education, Inc. All rights reserved.
124
2005 Pearson Education, Inc. All rights reserved.
125
Practical trainingPractical training
Read and run the following programs given to you :
ComputeGrade.java
CreditTest.java
LargestTest.java
SecDegEq.java
2005 Pearson Education, Inc. All rights reserved.
126
TEST
Write a program to process cars, each car has attributes
model : string
year : int
price : double
1- Write the class Car
2- Write the class TestCar , which has the main method
Ask the user to enter number of cars to process
input car information model, year, price
display the oldest car information
display the average price of cars
2005 Pearson Education, Inc. All rights reserved.
Question : We want to write a Java program that processes Vehicles as shown in the UML diagram. A Vehicle has a type that shows whether the vehicle is a car, a track or a bus. The bus has the attributes power and nbPassengers. The truck has the attributes power and load. The car has the attributes power and isLuxury. When the load of the vehicle is more than 2000kg and less than 3000kg, the vehicle is in the category of the MidSize Truck. When the load is more than 3000kg, the vehicle is in the category of the heavy truck.
•
•
• Write the Vehicle class.
• Using the class Vehicle, write the class VehicleProcess, that processes the following tasks:
–Read the required data vehicle.
–Displays the only required data of the processed vehicle
–If the entered data is related to a truck, displays its category according to its load.
127
+type:String+load:int+nbPassengers:int+power:int+isLuxury:Boolean
Vehicle
+main(String[] args):void()
VehicleProcess
2005 Pearson Education, Inc. All rights reserved.
• Question 2: We want to write a Java program that manages a Bookstore, we create the shown UML class Book containing the following attributes:
• Author: a string representing the author name of the book
• Price: the price of the book.
• PublishedYear: the publishing year of the book
•
• Write the class Book
• Using the class Book, write the class TestBook that processes the following tasks:
•Read the number of books in the bookStore.
•Read the information of each book.
•Display the number of books that were published before year 2000.
•Display the author name of the book that has the highest price.
128
Book
+ Author: String
+ PublishedYear: int
+ Price: double
TestBook
+ main(String[] args): void
2005 Pearson Education, Inc. All rights reserved.
The Definition of the Bicycle Class
import java.util.Scanner; // class uses class Scanner
class Book {
// Data Member public String Author;
public int PublishedYear ;public double Price ;
}
2005 Pearson Education, Inc. All rights reserved.
130
2005 Pearson Education, Inc. All rights reserved.
131
2005 Pearson Education, Inc. All rights reserved.
First Example: Using the Bicycle Class
import java.util.Scanner; // class uses class Scanner
class BicycleRegistration {
public static void main(String[] args) {
// create Scanner to obtain input from command window// create Scanner to obtain input from command window Scanner input = new Scanner( System.in );
int BooksNumber, BooksBefore2000Count = 0 ;
double highestPrice = 0.0;
String name;
// prompt user to // prompt user to Read the number of books in the bookStore.Read the number of books in the bookStore. System.out.print( "Enter the Number of Books in th store" );
BooksNumber = input.nextInt();
Book Mybook;
Mybook = new Book( ); //Create and assign values to Mybook
for ( int counter = 1; counter <= BooksNumber; counter++)
{
System.out.print( "Enter the Author Name of the Book" ); BooksNumber = input.nextInt();
Mybook.Author = input.next();
2005 Pearson Education, Inc. All rights reserved.
The Definition of the Bicycle Class
System.out.print( "Enter Published Year of the Book" );
Mybook. PublishedYear = input.nextInt();
System.out.print( "Enter Price of the Book" );
Mybook.Price = input.nextDouble();
If (Mybook.PublishedYear < 200 )
BooksBefore2000Count++;
If (Mybook.Price > highestPrice)
{ highestPrice = Mybook.Price ;
name = Mybook.Author ;}
} // end for
// Display the number of books that were published before year 2000.
System.out.println( “Number of books were published before year 2000” + BooksBefore2000Count );
// Display the author name of the book that has the highest price.
System.out.println(“The author name of the book that has the highest price” + name );
} // end main
} // end class
2005 Pearson Education, Inc. All rights reserved.
Question : Display the output of the following program.
public class Test {
public static void main(String[] args) {
int a=10, b=15, c=30; double x=9;
System.out.println(" Part A: ");
x = a/ 2 + b / 2 + x / 2 + b/ 2.0;
System.out.println(" first: x = "+ x );
if ( a > b || a -1 != 2 * b && b >= c )
{
x = a + c * a + 2;
System.out.println(" TRUE: x = " + x );
}else
System.out.println(" FALSE: x = " + (a+c * a + 2) );
System.out.println(" FINISH" );
}
}
134
2005 Pearson Education, Inc. All rights reserved.
135
2005 Pearson Education, Inc. All rights reserved.
136
2005 Pearson Education, Inc. All rights reserved.
137
2005 Pearson Education, Inc. All rights reserved.
138
2005 Pearson Education, Inc. All rights reserved.
139
END
of
Training Lecture
2005 Pearson Education, Inc. All rights reserved.
140
// GradeBook class
import java.util.Scanner; // program uses class Scanner
class GradeBook
{
// GradeBookTestExample3.java
// Create GradeBook object and invoke its determineClassAverage method.
•GradeBook.java
•(1 of 3)
Create object and invoke its method.Create object and invoke its method.
2005 Pearson Education, Inc. All rights reserved.
141
Outline28 // display a welcome message to the GradeBook user
29 public void displayMessage()
30 {
31 //
32 System.out.printf( "Welcome to the grade book for\n CSC111 \n");
33
34 } // end method displayMessage
35
36 // determine class average based on 10 grades entered by user
37 public void determineClassAverage()
38 {
39 // create Scanner to obtain input from command window
40 Scanner input = new Scanner( System.in );
41
42 int total; // sum of grades entered by user
43 int gradeCounter; // number of the grade to be entered next
44 int grade; // grade value entered by user
45 int average; // average of grades
46
47 // initialization phase
48 total = 0; // initialize total
49 gradeCounter = 1; // initialize loop counter
50
•GradeBook.java
•(2 of 3)
Declare method displayMessage
Declare method determineClassAverage
Declare and initialize Scanner variable input
Declare local int variables total, gradeCounter, grade and average
2005 Pearson Education, Inc. All rights reserved.
142
Outline51 // processing phase
52 while ( gradeCounter <= 10 ) // loop 10 times
53 {
54 System.out.print( "Enter grade: " ); // prompt
55 grade = input.nextInt(); // input next grade
56 total = total + grade; // add grade to total
57 gradeCounter = gradeCounter + 1; // increment counter by 1
58 } // end while
59
60 // termination phase
61 average = total / 10; // integer division yields integer result
62
63 // display total and average of grades
64 System.out.printf( "\nTotal of all 10 grades is %d\n", total );
65 System.out.printf( "Class average is %d\n", average );
66 } // end method determineClassAverage
67
68 } // end class GradeBook
•GradeBook.java
•(3 of 3)
while loop iterates as long as gradeCounter <= 10
Increment the counter variable gradeCounter
Calculate average grade
Display results
2005 Pearson Education, Inc. All rights reserved.
143
Outline 1 // GradeBookTestExample3.java
2 // Create GradeBook object and invoke its determineClassAverage method.
3
4 public class GradeBookTestExample3
5 {
6 public static void main( String args[] )
7 {
8 // create GradeBook object myGradeBook
9
10 GradeBook myGradeBook = new GradeBook();
12
13 myGradeBook.displayMessage(); // display welcome message
14 myGradeBook.determineClassAverage(); // find average of 10 grades
15 } // end main
16
17 } // end class GradeBookTest3
Welcome to the grade book for CSC111! Enter grade: 67 Enter grade: 78 Enter grade: 89 Enter grade: 67 Enter grade: 87 Enter grade: 98 Enter grade: 93 Enter grade: 85 Enter grade: 82 Enter grade: 100 Total of all 10 grades is 846 Class average is 84
Create a new GradeBook object
Call GradeBook’s determineClassAverage method
•GradeBookTestExample3.java
2005 Pearson Education, Inc. All rights reserved.
144
1 Initialize passes to zero 2 Initialize failures to zero 3 Initialize student counter to one 4 5 While student counter is less than or equal to 10 6 Prompt the user to enter the next exam result 7 Input the next exam result 8 9 If the student passed 10 Add one to passes 11 Else 12 Add one to failures 13 14 Add one to student counter 15 16 Print the number of passes 17 Print the number of failures 18 19 If more than eight students passed 20 Print “Raise tuition”
2005 Pearson Education, Inc. All rights reserved.
145
// Analysis of examination results.
import java.util.Scanner; // class uses class Scanner
class Analysis { public void processExamResults() {
// create Scanner to obtain input from command window Scanner input = new Scanner( System.in );
// initializing variables in declarations
int passes = 0; // number of passes
int failures = 0; // number of failures
int studentCounter = 1; // student counter
int result; // one exam result (obtains value from user)
Create object and invoke its method.Create object and invoke its method. AnalysisTestExample2
2005 Pearson Education, Inc. All rights reserved.
146
// process 10 students using counter-controlled loop
while ( studentCounter <= 10 ) { // prompt user for input and obtain value from user System.out.print( "Enter result " ); result = input.nextInt();
// if...else nested in while if ( result >= 60 ) // if result >60, passes = passes + 1; // increment passes; else // else result is not >=60, so failures = failures + 1; // increment failures
// increment studentCounter so loop eventually terminates studentCounter = studentCounter + 1;
} // end while
2005 Pearson Education, Inc. All rights reserved.
147
// termination phase; prepare and display results
System.out.printf( "Passed: %d\nFailed: %d\n", passes, failures );
// determine whether more than 8 students passed
if ( passes > 8 ) System.out.println( "Raise Tuition" );
} // end method processExamResults
} // end class Analysis
2005 Pearson Education, Inc. All rights reserved.
148
// Test program for class Analysis.
public class AnalysisTestExample2 {
public static void main( String args[] ) { Analysis application = new Analysis(); // create Analysis object application.processExamResults(); // call method to process results
} // end main
} // end class AnalysisTestExample2
2005 Pearson Education, Inc. All rights reserved.
149
1 Initialize passes to zero 2 Initialize failures to zero 3 Initialize student counter to one 4 5 While student counter is less than or equal to 10 6 Prompt the user to enter the next exam result 7 Input the next exam result 8 9 If the student passed 10 Add one to passes 11 Else 12 Add one to failures 13 14 Add one to student counter 15 16 Print the number of passes 17 Print the number of failures 18 19 If more than eight students passed 20 Print “Raise tuition”
2005 Pearson Education, Inc. All rights reserved.
150
Outline 1
2 // Analysis of examination results.
3 import java.util.Scanner; // class uses class Scanner
4
5 class Analysis
6 {
7 public void processExamResults
8 {
9 // create Scanner to obtain input from command window
10 Scanner input = new Scanner( System.in );
11
12 // initializing variables in declarations
13 int passes = 0; // number of passes
14 int failures = 0; // number of failures
15 int studentCounter = 1; // student counter
16 int result; // one exam result (obtains value from user)
17
18 // process 10 students using counter-controlled loop
19 while ( studentCounter <= 10 )
20 {
21 // prompt user for input and obtain value from user
22 System.out.print( "Enter result (1 = pass, 2 = fail): " );
23 result = input.nextInt();
24
Declare processExamResults’ local variables
while loop iterates as long as studentCounter <= 10
2005 Pearson Education, Inc. All rights reserved.
151
Outline
•Analysis.java
•(2 of 2)
25 // if...else nested in while
26 if ( result == 1 ) // if result 1,
27 passes = passes + 1; // increment passes;
28 else // else result is not 1, so
29 failures = failures + 1; // increment failures
30
31 // increment studentCounter so loop eventually terminates
32 studentCounter = studentCounter + 1;
33 } // end while
34
35 // termination phase; prepare and display results
36 System.out.printf( "Passed: %d\nFailed: %d\n", passes, failures );
37
38 // determine whether more than 8 students passed
39 if ( passes > 8 )
40 System.out.println( "Raise Tuition" );
41 } // end method processExamResults
42
43 } // end class Analysis
Determine whether this student passed or failed and increment the appropriate variable
Determine whether more than eight students passed the exam
2005 Pearson Education, Inc. All rights reserved.
152
Outline 1 // AnalysisTest2.java 2 // Test program for class Analysis. 3 4 public class AnalysisTest2 5 { 6 public static void main( String args[] ) 7 { 8 Analysis application = new Analysis(); // create Analysis object 9 application.processExamResults(); // call method to process results 10 } // end main 11 12 } // end class AnalysisTest2
Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Passed: 9 Failed: 1 Raise Tuition Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Passed: 6 Failed: 4
Create an Analysis object
More than 8 students passed the exam
AnalysisTest2.java
2005 Pearson Education, Inc. All rights reserved.
153
Formulating Algorithms: Sentinel-Controlled Repetition
• Sentinel-controlled repetition– Also known as indefinite repetition
– Use a sentinel value (also known as a signal, dummy or flag value)
• A sentinel value cannot also be a valid input value
2005 Pearson Education, Inc. All rights reserved.
154
Fig. 4.8 | Class-average problem pseudocode algorithm with sentinel-controlled repetition.
1 Initialize total to zero
2 Initialize counter to zero
3
4 Prompt the user to enter the first grade
5 Input the first grade (possibly the sentinel)
6
7 While the user has not yet entered the sentinel
8 Add this grade into the running total
9 Add one to the grade counter
10 Prompt the user to enter the next grade
11 Input the next grade (possibly the sentinel)
12
13 If the counter is not equal to zero
14 Set the average to the total divided by the counter
15 Print the average
16 else
17 Print “No grades were entered”
2005 Pearson Education, Inc. All rights reserved.
155
Outline
•GradeBook.java
•(1 of 3)
1 // : GradeBook.java
2 // GradeBook class that solves class-average program using
3 // sentinel-controlled repetition.
4 import java.util.Scanner; // program uses class Scanner
5
6 public class GradeBook
7 {
2005 Pearson Education, Inc. All rights reserved.
156
Outline
•GradeBook.java
•(2 of 3)
28 // display a welcome message to the GradeBook user
29 public void displayMessage()
30 {
31 // getCourseName gets the name of the course
32 System.out.printf( "Welcome to the grade book for\n CSC111!\n\n",
33 getCourseName() );
34 } // end method displayMessage
35
36 // determine the average of an arbitrary number of grades
37 public void determineClassAverage()
38 {
39 // create Scanner to obtain input from command window
40 Scanner input = new Scanner( System.in );
41
42 int total; // sum of grades
43 int gradeCounter; // number of grades entered
44 int grade; // grade value
45 double average; // number with decimal point for average
46
47 // initialization phase
48 total = 0; // initialize total
49 gradeCounter = 0; // initialize loop counter
50
51 // processing phase
52 // prompt for input and read grade from user
53 System.out.print( "Enter grade or -1 to quit: " );
54 grade = input.nextInt();
55
Declare method displayMessage
Declare method determineClassAverage
Declare and initialize Scanner variable input
Declare local int variables total, gradeCounter and grade and double variable average
2005 Pearson Education, Inc. All rights reserved.
157
Outline
•GradeBook.java
•(3 of 3)
56 // loop until sentinel value read from user
57 while ( grade != -1 )
58 {
59 total = total + grade; // add grade to total
60 gradeCounter = gradeCounter + 1; // increment counter
61
62 // prompt for input and read next grade from user
63 System.out.print( "Enter grade or -1 to quit: " );
64 grade = input.nextInt();
65 } // end while
66
67 // termination phase
68 // if user entered at least one grade...
69 if ( gradeCounter != 0 )
70 {
71 // calculate average of all grades entered
72 average = (double) total / gradeCounter;
73
74 // display total and average (with two digits of precision)
75 System.out.printf( "\nTotal of the %d grades entered is %d\n",
76 gradeCounter, total );
77 System.out.printf( "Class average is %.2f\n", average );
78 } // end if
79 else // no grades were entered, so output appropriate message
80 System.out.println( "No grades were entered" );
81 } // end method determineClassAverage
82
83 } // end class GradeBook
while loop iterates as long as grade != the sentinel value, -1
Calculate average grade using (double) to perform explicit conversion
Display average grade
Display “No grades were entered” message
2005 Pearson Education, Inc. All rights reserved.
158
Outline 1 // GradeBookTest4.java
2 // Create GradeBook object and invoke its determineClassAverage method.
3
4 public class GradeBookTest4
5 {
6 public static void main( String args[] )
7 {
8 // create GradeBook object myGradeBook and
9 // pass course name to constructor
10 GradeBook myGradeBook = new GradeBook();
11
12
13 myGradeBook.displayMessage(); // display welcome message
14 myGradeBook.determineClassAverage(); // find average of grades
15 } // end main
16
17 } // end class GradeBookTest4
Welcome to the grade book for CS111 Enter grade or -1 to quit: 97 Enter grade or -1 to quit: 88 Enter grade or -1 to quit: 72 Enter grade or -1 to quit: -1 Total of the 3 grades entered is 257 Class average is 85.67
Create a new GradeBook object
Call GradeBook’s determineClassAverage method
•GradeBookTest4.java
2005 Pearson Education, Inc. All rights reserved.
159
do…while Repetition Statement
• do…while structure–Similar to while structure
–Tests loop-continuation after performing body of loop•i.e., loop body always executes at least once
2005 Pearson Education, Inc. All rights reserved.
160
Outline• DoWhileTest.java
• Line 8• Lines 10-
14
• Program output
1 // Fig. 5.7: DoWhileTest.java
2 // do...while repetition statement.
3
4 public class DoWhileTest
5 {
6 public static void main( String args[] )
7 {
8 int counter = 1; // initialize counter
9
10 do
11 {
12 System.out.printf( "%d ", counter );
13 ++counter;
14 } while ( counter <= 10 ); // end do...while
15
16 System.out.println(); // outputs a newline
17 } // end main
18 } // end class DoWhileTest 1 2 3 4 5 6 7 8 9 10
Declares and initializes control variable counter
Variable counter’s value is displayed before testing counter’s final value
161
Fig. 5.8 | do...while repetition statement UML activity diagram.
do {
System.out.printf( "%d ", counter );
++counter;
} while ( counter <= 10 ); // end do...while
2005 Pearson Education, Inc. All rights reserved.
162
Good Programming Practice
• Always include braces in a do...while statement, even if they are not necessary. This helps eliminate ambiguity between the while statement and a do...while statement containing only one statement.