You are on page 1of 96

Dao Tran Hoang Chau, MSc

School of Computer Science and Engineering, HCMC International University

OBJECT-ORIENTED PROGRAMMING
C O N T R O L S T A T E M E N T S , A R R AY S

ALGORITHMS
Algorithms
The actions to execute The order in which these actions execute

Program control
Specifies the order in which actions execute in a program

PSEUDOCODE
Pseudocode
An informal language similar to English Helps programmers develop algorithms Does not run on computers

CONTROL STRUCTURES
Sequential execution
Statements are normally executed one after the other in the order in which they are written

Transfer of control
Can be performed by the goto statement
Structured programming eliminated goto statements

CONTROL STRUCTURES (CONT.)


UML activity diagram (www.uml.org)
Models the workflow (or activity) of a part of a software system Action-state symbols (rectangles with their sides replaced with outward-curving arcs)
represent action expressions specifying actions to perform

Diamonds
Decision symbols
Merge symbols
6

SEQUENCE STRUCTURE ACTIVITY DIAGRAM.

CONTROL STRUCTURES (CONT.)


Selection Statements
if statement
Single-selection statement

ifelse statement
Double-selection statement

switch statement
Multiple-selection statement

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

dowhile statement
Performs the actions in its body one or more times

for statement
Performs the actions in its body zero or more times

10

CONTROL STRUCTURES (CONT.)


Java has three kinds of control structures
Sequence statement, Selection statements (three types) and Repetition statements (three types) All programs are composed of these control statements
Control-statement nesting

11

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

12

SINGLE-SELECTION STATEMENT UML ACTIVITY DIAGRAM.

13

IFELSE DOUBLE-SELECTION STATEMENT


ifelse statement
Executes one action if the specified condition is true or a different action if the specified condition is false

Conditional Operator ( ? : )
Javas only ternary operator (takes three operands) ? : and its three operands form a conditional expression
Entire conditional expression evaluates to the second operand if the first operand is true Entire conditional expression evaluates to the third operand if the first operand is false
14

GOOD PROGRAMMING PRACTICES


Conditional expressions are more difficult to read than if else statements and should be used to replace

only simple if else statements that choose between


two values.

15

STATEMENT UML ACTIVITY DIAGRAM.

IF ELSE DOUBLE-SELECTION

16

IFELSE DOUBLE-SELECTION STATEMENT (CONT.)


Nested ifelse statements
ifelse statements can be put inside other ifelse statements

Dangling-else problem
elses are always associated with the immediately preceding if unless otherwise specified by braces { }

Blocks
Braces { } associate statements into blocks
17

IFELSE DOUBLE-SELECTION STATEMENT (CONT.)


Logic errors
Fatal logic errors cause a program to fail and terminate prematurely Nonfatal logic errors cause a program to produce incorrect results

Empty statements
Represented by placing a semicolon ( ; ) where a statement would normally be Can be used as an if body
18

GOOD PROGRAMMING PRACTICES


Forgetting one or both of the braces that delimit a block can lead to syntax errors or logic errors in a program. To avoid omitting one or both of the braces, some programmers type the beginning and ending braces of blocks before typing the individual statements

within the braces.

19

WHILE REPETITION STATEMENT


while statement
Repeats an action while its loop-continuation condition remains true Uses a merge symbol in its UML activity diagram
Merges two or more workflows Represented by a diamond (like decision symbols) but has:
Multiple incoming transition arrows,

Only one outgoing transition arrow and


No guard conditions on any transition arrows
20

COMMON PROGRAMMING ERROR


Not providing, in the body of a while statement, an action that eventually causes the condition in the while to become false normally results in a logic error called an infinite loop, in which the loop never terminates.

21

WHILE

REPETITION STATEMENT UML ACTIVITY DIAGRAM.

22

PSEUDOCODE ALGORITHM TO SOLVE THE CLASS-AVERAGE PROBLEM.


1 Set total to zero

2
3 4 5 6 7 8

Set grade counter to one

While grade counter is less than or equal to ten Prompt the user to enter the next grade Input the next grade Add the grade into the total Add one to the grade counter

9
10 11 Set the class average to the total divided by ten Print the class average
24

OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // method to retrieve the course name public String getCourseName() { return courseName; } // end method getCourseName // method to set the course name public void setCourseName( String name ) { courseName = name; // store the course name } // end method setCourseName // constructor initializes courseName public GradeBook( String name ) { } // end constructor public class GradeBook { private String courseName; // name of course this GradeBook represents // Fig. 4.6: GradeBook.java // GradeBook class that solves class-average problem using // counter-controlled repetition. import java.util.Scanner; // program uses class Scanner

Assign a value to instance variable courseName

courseName = name; // initializes courseName

Declare method setCourseName

Declare method getCourseName

25

OUTLINE
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 // initialization phase total = 0; // initialize total gradeCounter = 1; // initialize loop counter 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 // determine class average based on 10 grades entered by user public void determineClassAverage() { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); // 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 for\n%s!\n\n", getCourseName() ); } // end method displayMessage

Declare method displayMessage

Declare method determineClassAverage

Declare and initialize Scanner variable input

Declare local int variables total, gradeCounter, grade and average 26

OUTLINE
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 } // end class GradeBook // 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 method determineClassAverage // termination phase average = total / 10; // integer division yields integer result // processing phase while ( gradeCounter <= 10 ) // loop 10 times { System.out.print( "Enter grade: " ); // prompt grade = input.nextInt(); // input next grade total = total + grade; // add grade to total gradeCounter = gradeCounter + 1; // increment counter by 1 } // end while

while loop iterates as long as gradeCounter <= 10

Increment the counter variable gradeCounter

Calculate average grade

Display results

27

GOOD PROGRAMMING PRACTICES


Separate declarations from other statements in methods with a blank line for readability. Experience has shown that the most difficult part of solving a problem on a computer is developing the algorithm for the solution. Once a correct algorithm has been specified, the process of producing a

working Java program from the algorithm is normally


straightforward.
28

GOOD PROGRAMMING PRACTICES


All local variables must be initialized before their values are used in expressions. Initialize each counter and total, either in its declaration or in an assignment statement

29

OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 } // end class GradeBookTest Welcome to the grade book for CS101 Introduction to Java Programming! Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter grade: grade: grade: grade: grade: grade: grade: grade: grade: grade: 67 78 89 67 87 98 93 85 82 100 myGradeBook.displayMessage(); // display welcome message myGradeBook.determineClassAverage(); // find average of 10 grades } // end main public class GradeBookTest { public static void main( String args[] ) { // create GradeBook object myGradeBook and // pass course name to constructor GradeBook myGradeBook = new GradeBook( // Fig. 4.7: GradeBookTest.java // Create GradeBook object and invoke its determineClassAverage method.

Create a new GradeBook object

IT069 Object-Oriented Programming "CS101 Introduction to Java Programming" );

Pass the courses name to the GradeBook constructor as a string

Call GradeBooks determineClassAverage method

Total of all 10 grades is 846 Class average is 84

30

FORMULATING ALGORITHMS: SENTINELCONTROLLED 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

32

SOFTWARE ENGINEERING OBSERVATIONS


Many programs can be divided logically into three phases:
an initialization phase that initializes the variables; a processing phase that inputs data values and adjusts program variables (e.g., counters and totals) accordingly; and a termination phase that calculates and outputs the final results.

34

ERROR-PREVENTION TIP
When performing division by an expression whose value could be zero, explicitly test for this possibility and handle it appropriately in your program (e.g., by printing an error message) rather than allow the error to occur

35

OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // Fig. 4.9: GradeBook.java // GradeBook class that solves class-average program using // sentinel-controlled repetition. import java.util.Scanner; // program uses class Scanner public class GradeBook { private String courseName; // name of course this GradeBook represents // constructor initializes courseName public GradeBook( String name ) { courseName = name; // initializes courseName } // end constructor // method to set the course name public void setCourseName( String name ) { courseName = name; // store the course name } // end method setCourseName // method to retrieve the course name public String getCourseName() { return courseName; } // end method getCourseName

Assign a value to instance variable courseName Declare method setCourseName

Declare method getCourseName


38

Declare method displayMessage

OUTLINE
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 // 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 for\n%s!\n\n", getCourseName() ); } // end method displayMessage // determine the average of an arbitrary number of grades public void determineClassAverage() { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int total; // sum of grades int gradeCounter; // number of grades entered int grade; // grade value double average; // number with decimal point for average // initialization phase total = 0; // initialize total gradeCounter = 0; // initialize loop counter // processing phase // prompt for input and read grade from user System.out.print( "Enter grade or -1 to quit: " ); grade = input.nextInt();

Declare method determineClassAverage Declare and initialize Scanner variable input

Declare local int variables total, gradeCounter and grade and double variable average

39

OUTLINE
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 } // end class GradeBook // display total and average (with two digits of precision) System.out.printf( "\nTotal of the %d grades entered is %d\n", gradeCounter, total ); System.out.printf( "Class average is %.2f\n", average ); } // end if else // no grades were entered, so output appropriate message System.out.println( "No grades were entered" ); } // end method determineClassAverage // termination phase // if user entered at least one grade... if ( gradeCounter != 0 ) { // calculate average of all grades entered average = (double) total / gradeCounter; // prompt for input and read next grade from user System.out.print( "Enter grade or -1 to quit: " ); grade = input.nextInt(); } // end while // loop until sentinel value read from user while ( grade != -1 ) { total = total + grade; // add grade to total gradeCounter = gradeCounter + 1; // increment counter

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


40

GOOD PROGRAMMING PRACTICES


In a sentinel-controlled loop, the prompts requesting data entry should explicitly remind the user of the sentinel value. Omitting the braces that delimit a block can lead to logic errors, such as infinite loops. To prevent this problem, some programmers enclose the body of

every control statement in braces even if the body


contains only a single statement.
41

FORMULATING ALGORITHMS: NESTED CONTROL STATEMENTS


Control statements can be nested within one another
Place one control statement inside the body of the other

45

PSEUDOCODE FOR EXAMINATION-RESULTS PROBLEM.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Initialize passes to zero Initialize failures to zero Initialize student counter to one While student counter is less than or equal to 10 Prompt the user to enter the next exam result Input the next exam result If the student passed Add one to passes Else Add one to failures Add one to student counter Print the number of passes Print the number of failures If more than eight students passed Print Raise tuition
46

OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // process 10 students using counter-controlled loop while ( studentCounter <= 10 ) { // prompt user for input and obtain value from user System.out.print( "Enter result (1 = pass, 2 = fail): " ); result = input.nextInt(); // 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) public class Analysis { public void processExamResults { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); // Fig. 4.12: Analysis.java // Analysis of examination results. import java.util.Scanner; // class uses class Scanner

while loop iterates as long as studentCounter <= 10

47

OUTLINE
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 } // end class Analysis // determine whether more than 8 students passed if ( passes > 8 ) System.out.println( "Raise Tuition" ); } // end method processExamResults // termination phase; prepare and display results // increment studentCounter so loop eventually terminates studentCounter = studentCounter + 1; } // end while // if...else nested in while if ( result == 1 ) passes = passes + 1; else // if result 1, // increment passes; // else result is not 1, so

failures = failures + 1; // increment failures

Determine whether this student passed or failed and increment the appropriate variable

System.out.printf( "Passed: %d\nFailed: %d\n", passes, failures );

Determine whether more than eight students passed the exam

48

ERROR-PREVENTION TIP
Initializing local variables when they are declared helps the programmer avoid any compilation errors that might arise from attempts to use uninitialized data. 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.
49

OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 // Fig. 4.13: AnalysisTest.java // Test program for class Analysis.

Create an Analysis object

public class AnalysisTest { public static void main( String args[] ) { Analysis application = new Analysis(); // create Analysis object application.processExamResults(); // call method to process results } // end main } // end class AnalysisTest = = = = = = = = = = pass, pass, pass, pass, pass, pass, pass, pass, pass, pass, 2 2 2 2 2 2 2 2 2 2 = = = = = = = = = = fail): fail): fail): fail): fail): fail): fail): fail): fail): fail): 1 2 1 1 1 1 1 1 1 1

Enter result (1 Enter result (1 Enter result (1 Enter result (1 Enter result (1 Enter result (1 Enter result (1 Enter result (1 Enter result (1 Enter result (1 Passed: 9 Failed: 1 Raise Tuition Enter result Enter result Enter result Enter result Enter result Enter result Enter result Enter result Enter result Enter result Passed: 6 Failed: 4 (1 (1 (1 (1 (1 (1 (1 (1 (1 (1

More than 8 students passed the exam


= = = = = = = = = = pass, pass, pass, pass, pass, pass, pass, pass, pass, pass, 2 2 2 2 2 2 2 2 2 2 = = = = = = = = = = fail): fail): fail): fail): fail): fail): fail): fail): fail): fail): 1 2 1 2 1 2 2 1 1 1

50

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

51

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
53

GOOD PROGRAMMING PRACTICES


Unlike binary operators, the unary increment and decrement operators should be placed next to their operands, with NO intervening spaces.

54

OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 5 5 6 5 6 6 // Fig. 4.16: Increment.java // Prefix increment and postfix increment operators. public class Increment { public static void main( String args[] ) { int c; // demonstrate postfix increment operator c = 5; // assign 5 to c System.out.println( c ); // print 5 System.out.println( c++ ); // print 5 then postincrement System.out.println( c ); // print 6 System.out.println(); // skip a line // demonstrate prefix increment operator c = 5; // assign 5 to c System.out.println( c ); // print 5 System.out.println( ++c ); // preincrement then print 6 System.out.println( c ); // print 6 } // end main } // end class Increment

Postincrementing the c variable

Preincrementing the c variable

56

PRECEDENCE AND ASSOCIATIVITY OF THE OPERATORS DISCUSSED SO FAR.

Operators
++ ++ * + < == ?: = --/ <= != += + % > ( type )

Associativity
right to left right to left left to right left to right left to right left to right right to left %= right to left

Type
unary postfix unary prefix Multiplicative Additive Relational Equality Conditional assignment

>=

-=

*=

/=

58

PRIMITIVE TYPES
Java is a strongly typed language
All variables have a type

Primitive types in Java are portable across all platforms that support Java

59

FOR REPETITION STATEMENT


Handles counter-controlled-repetition details

67

OUTLINE
1 // Fig. 5.2: ForCounter.java 2 // Counter-controlled repetition with the for repetition statement. 3 4 public class ForCounter 5 { 6 7 8 9 10 11 12 13 System.out.println(); // output a newline 14 } // end main Control-variable name is 15 } // end class ForCounter 1 2 3 4 5 6 7 8 9 10 public static void main( String args[] ) { // for statement header includes initialization, // loop-continuation condition and increment for ( int counter = 1; counter <= 10; counter++ ) System.out.printf( "%d ", counter );

counter Increment for counter

Control-variable initial value is 1

Condition tests for counters final value

68

FOR REPETITION STATEMENT (CONT.)


for ( initialization; loopContinuationCondition; increment ) statement; can usually be rewritten as: initialization; while ( loopContinuationCondition ) { statement; increment; }
71

UML ACTIVITY DIAGRAM FOR THE FOR STATEMENT

75

EXAMPLES USING THE FOR STATEMENT


Varying control variable in for statement
Vary control variable from 1 to 100 in increments of 1
for ( int i = 1; i <= 100; i++ )

Vary control 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 )
76

OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // Fig. 5.5: Sum.java // Summing integers with the for statement. public class Sum { public static void main( String args[] ) { int total = 0; // initialize total // total even integers from 2 through 20 for ( int number = 2; number <= 20; number += 2 ) total += number; System.out.printf( "Sum is %d\n", total ); // display results } // end main

16 } // end class Sum Sum is 110

increment number by 2 each iteration

78

EXAMPLES USING THE FOR STATEMENT (CONT.)


Initialization and increment expression can be comma-separated lists of expressions
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

79

OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 // display headers System.out.printf( "%s%20s\n", "Year", "Amount on deposit" ); public class Interest { { double amount; // amount on deposit at end of each year double principal = 1000.0; // initial amount before interest double rate = 0.05; // interest rate // Fig. 5.6: Interest.java // Compound-interest calculations with for.

public static void main( String args[] )

Java treats floating-points as type double

Second string is right justified and displayed with a field width of 20

81

OUTLINE
15 16 17 18 19 20 21 22 23 24 // display the year and the amount System.out.printf( "%4d%,20.2f\n", year, amount ); } // end for } // end main // calculate amount on deposit for each of ten years for ( int year = 1; year <= 10; year++ ) { // calculate new amount for specified year amount = principal * Math.pow( 1.0 + rate, year );

Calculate amount with for statement

25 } // end class Interest Year 1 2 3 4 5 6 7 8 9 10 Amount on deposit 1,050.00 1,102.50 1,157.63 1,215.51 1,276.28 1,340.10 1,407.10 1,477.46 1,551.33 1,628.89

Use the comma (,) formatting flag to display the amount with a thousands separator

82

EXAMPLES USING THE FOR STATEMENT (CONT.)


Formatting output
Field width Minus sign (-) formatting flag Comma (,) formatting flag

static method
ClassName.methodName( arguments)

83

DOWHILE REPETITION STATEMENT


dowhile structure
Similar to while structure Tests loop-continuation after performing body of loop
i.e., loop body always executes at least once

85

OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // Fig. 5.7: DoWhileTest.java // do...while repetition statement. public class DoWhileTest { public static void main( String args[] ) { int counter = 1; // initialize counter do { System.out.printf( "%d ++counter; ", counter );

Declares and initializes control variable counter

Variable counters value is displayed before testing counters final value

} while ( counter <= 10 ); // end do...while System.out.println(); // outputs a newline } // end main

18 } // end class DoWhileTest 1 2 3 4 5 6 7 8 9 10


86

DO...WHILE

REPETITION STATEMENT UML ACTIVITY DIAGRAM.

87

GOOD PROGRAMMING PRACTICES


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.

88

SWITCH MULTIPLE-SELECTION STATEMENT


switch statement
Used for multiple selections

89

OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // Fig. 5.9: GradeBook.java // GradeBook class uses switch statement to count A, B, C, D and F grades. import java.util.Scanner; // program uses class Scanner public class GradeBook { private String courseName; // name of course this GradeBook represents private int total; // sum of grades private int gradeCounter; // number of grades entered private int aCount; // count of A grades private int bCount; // count of B grades private int cCount; // count of C grades private int dCount; // count of D grades private int fCount; // count of F grades // constructor initializes courseName; // int instance variables are initialized to 0 by default public GradeBook( String name ) { courseName = name; // initializes courseName } // end constructor // method to set the course name public void setCourseName( String name ) { courseName = name; // store the course name } // end method setCourseName

90

OUTLINE
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 // method to retrieve the course name public String getCourseName() { return courseName; } // end method getCourseName // 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 for\n%s!\n\n", getCourseName() ); } // end method displayMessage // input arbitrary number of grades from user public void inputGrades() { Scanner input = new Scanner( System.in ); int grade; // grade entered by user System.out.printf( "%s\n%s\n %s\n %s\n",

"Enter the integer grades in the range 0-100.", "Type the end-of-file indicator to terminate input:", "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter", "On Windows type <ctrl> z then press Enter" );

91

OUTLINE
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 // loop until user enters the end-of-file indicator while ( input.hasNext() ) Loop condition uses method hasNext to { grade = input.nextInt(); // read grade determine whether there is more data to input total += grade; // add grade to total ++gradeCounter; // increment number of grades // call method to increment appropriate counter incrementLetterGradeCounter( grade ); } // end while } // end method inputGrades // add 1 to appropriate counter for specified grade public void incrementLetterGradeCounter( int numericGrade ) { (grade / 10 ) is // determine which grade was entered controlling expression switch ( grade / 10 ) { case 9: // grade was between 90 switch statement determines case 10: // and 100 which case label to execute, ++aCount; // increment aCount depending on controlling expression break; // necessary to exit switch case 8: // grade was between 80 and 89 ++bCount; // increment bCount break; // exit switch

92

OUTLINE
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 case 7: // grade was between 70 and 79 ++cCount; // increment cCount break; // exit switch case 6: // grade was between 60 and 69 ++dCount; // increment dCount break; // exit switch default: // grade was less than 60 ++fCount; // increment fCount break; // optional; will exit switch anyway } // end switch } // end method incrementLetterGradeCounter // display a report based on the grades entered by user public void displayGradeReport() { System.out.println( "\nGrade Report:" ); // if user entered at least one grade... if ( gradeCounter != 0 ) { // calculate average of all grades entered double average = (double) total / gradeCounter;

default case for grade less than 6

93

OUTLINE
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 // output summary of results System.out.printf( "Total of the %d grades entered is %d\n", gradeCounter, total ); System.out.printf( "Class average is %.2f\n", average ); System.out.printf( "%s\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n", "Number of students who received each grade:", "A: ", aCount, "B: ", bCount, "C: ", cCount, "D: ", dCount, } // end if else // no grades were entered, so output appropriate message System.out.println( "No grades were entered" ); } // end method displayGradeReport // display number of A grades // display number of B grades // display number of C grades // display number of D grades

"F: ", fCount ); // display number of F grades

123 } // end class GradeBook

94

GOOD PROGRAMMING PRACTICES


The keystroke combinations for entering end-of-file are system dependent.

Forgetting a break statement when one is needed in a switch is a logic error.

95

SOFTWARE ENGINEERING OBSERVATIONS


Provide a default case in switch statements. Including a default case focuses you on the need to process exceptional conditions.

98

SWITCH MULTIPLE-SELECTION STATEMENT UML ACTIVITY DIAGRAM WITH BREAK STATEMENTS.

99

GOOD PROGRAMMING PRACTICES


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.

100

Loop 10 times OUTLINE (break) Exit for statement when count equals 5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // Fig. 5.12: BreakTest.java // break statement exiting a for statement. public class BreakTest { public static void main( String args[] ) { int count; // control variable also used after loop terminates for ( count = 1; count <= 10; count++ ) // loop 10 times { if ( count == 5 ) // if count is 5, break; // terminate loop System.out.printf( "%d ", count ); } // end for

BreakTest .java Line 9 Lines 1112

System.out.printf( "\nBroke out of loop at count = %d\n", count ); } // end main } // end class BreakTest

Program output

1 2 3 4 Broke out of loop at count = 5

103

OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 System.out.printf( "%d ", count ); } // end for public class ContinueTest { public static void main( String args[] ) {

Loop 10 times

Skip line 12 and proceed to line 7 when count equals 5


// Fig. 5.13: ContinueTest.java // continue statement terminating an iteration of a for statement.

Continue Test.java Line 7 Lines 910

for ( int count = 1; count <= 10; count++ ) // loop 10 times { if ( count == 5 ) // if count is 5, continue; // skip remaining code in loop

System.out.println( "\nUsed continue to skip printing 5" ); } // end main

17 } // end class ContinueTest 1 2 3 4 6 7 8 9 10 Used continue to skip printing 5

Program output

104

SOFTWARE ENGINEERING OBSERVATIONS


Some programmers feel that break and continue violate structured programming. Since the same effects are achievable with structured programming techniques, these programmers do not use break or continue. There is a tension between achieving quality

software engineering and achieving the bestperforming software. Often, one of these goals is achieved at the expense of the other. For all but the
105

5.8 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)
106

5.8 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

107

FIG. 5.14

| && (CONDITIONAL AND) OPERATOR TRUTH TABLE.

expression1 expression2 expression1 && expression2


false false true true false true false true False False False True

108

5.8 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

109

FIG. 5.15

| || (CONDITIONAL OR) OPERATOR TRUTH TABLE.

expression1
false false true true

expression2
false true false true

expression1 || expression2
false true true true

110

5.8 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

111

COMMON PROGRAMMING ERRORS


In expressions using operator &&, a condition - we will call this the dependent condition - may require another condition to be true for the evaluation of the dependent condition to be meaningful. In this case, the dependent condition should be placed after the other condition, or an error might

occur.
For example, in the expression ( i != 0 ) && ( 10 / i == 2 ), the second condition must appear
112

5.8 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

113

ERROR-PREVENTION TIPS
For clarity, avoid expressions with side effects in conditions. The side effects may look clever, but they can make it harder to understand code and can lead to subtle logic errors.

114

5.8 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

115

FIG. 5.16

| ^ (BOOLEAN LOGICAL EXCLUSIVE OR) OPERATOR TRUTH TABLE.

expression1
false false true true

expression2
false true false true

expression1 ^ expression2
false true true false

116

|! (LOGICAL NEGATION, OR LOGICAL NOT) OPERATOR TRUTH TABLE.


FIG. 5.17

expression
false true

!expression
true false

117

OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // create truth table for & (boolean logical AND) operator System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Boolean logical AND (&)", "false & false", ( false & false ), "false & true", ( false & true ), "true & false", ( true & false ), "true & true", ( true & true ) ); // create truth table for || (conditional OR) operator System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Conditional OR (||)", "false || false", ( false || false ), "false || true", ( false || true ), "true || false", ( true || false ), "true || true", ( true || true ) ); public class LogicalOperators { public static void main( String args[] ) { // create truth table for && (conditional AND) operator System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Conditional AND (&&)", "false && false", ( false && false ), "false && true", ( false && true ), "true && false", ( true && false ), "true && true", ( true && true ) ); // Fig. 5.18: LogicalOperators.java // Logical operators.

LogicalOp erators. java


(1 of 3) Lines 9-13 Conditional AND truth table Lines 16-20 Lines 23-27 Conditional OR truth table

Boolean logical AND truth table


118

OUTLINE
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 // create truth table for ! (logical negation) operator "Boolean logical inclusive OR (|)", "false | false", ( false | false ), "false | true", ( false | true ), "true | false", ( true | false ), "true | true", ( true | true ) );

Boolean logical inclusive LogicalOp OR truth table (2 of 3) Lines 30-35

// create truth table for | (boolean logical inclusive OR) operator System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n",

erators. java

Boolean logical exclusive Lines 38-43 OR truth table Lines 46-47

// create truth table for ^ (boolean logical exclusive OR) operator System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Boolean logical exclusive OR (^)", "false ^ false", ( false ^ false ), "false ^ true", ( false ^ true ), "true ^ false", ( true ^ false ), "true ^ true", ( true ^ true ) );

Logical negation truth table

System.out.printf( "%s\n%s: %b\n%s: %b\n", "Logical NOT (!)", "!false", ( !false ), "!true", ( !true ) ); } // end main

49 } // end class LogicalOperators

119

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

LogicalOp erators. java


(3 of 3) Program output

120

FIG. 5.19

| PRECEDENCE/ASSOCIATIVITY OF THE OPERATORS DISCUSSED SO FAR.


Operators
++ -++ (type) * / + < <= == != & ^ | && || ?: = += + % > >= !

Associativity Type
right to left right to left left to right left to right left to right left to right left to right left to right left to right left to right left to right right to left right to left unary postfix unary prefix multiplicative additive relational equality boolean logical AND boolean logical exclusive OR boolean logical inclusive OR conditional AND conditional OR conditional assignment

-=

*=

/=

%=

121

5.9 STRUCTURED PROGRAMMING SUMMARY


Sequence structure
built-in to Java

Selection structure
if, ifelse and switch

Repetition structure
while, dowhile and for

122

FIG. 5.20

| JAVAS SINGLE-ENTRY/SINGLEEXIT SEQUENCE, SELECTION AND REPETITION STATEMENTS.

123

FIG. 5.21

| RULES FOR FORMING STRUCTURED PROGRAMS.

Rules for Forming Structured Programs


1 2 3 Begin with the simplest activity diagram (Fig. 5.22). Any action state can be replaced by two action states in sequence. Any action state can be replaced by any control statement (sequence of action states, if, if else, switch, while, do while or for). 4 Rules 2 and 3 can be applied as often as you like and in any order.

124

FIG. 5.22

| SIMPLEST ACTIVITY DIAGRAM.

125

| REPEATEDLY APPLYING THE STACKING RULE (RULE 2) OF FIG. 5.21 TO THE SIMPLEST ACTIVITY DIAGRAM.
FIG. 5.23

126

| REPEATEDLY APPLYING THE NESTING RULE (RULE 3) OF FIG. 5.21 TO THE SIMPLEST ACTIVITY DIAGRAM.
FIG. 5.24

127

FIG. 5.25

| UNSTRUCTURED ACTIVITY DIAGRAM.

128

You might also like