710 likes | 715 Views
Chapter 4. Control Structures Decisions Loops. Chapter 4 selection structures. This chapter begins a new path in our programming ability Basically we can cause our programs to follow different paths, react differently to different situations.
E N D
Chapter 4 • Control Structures • Decisions • Loops
Chapter 4 selection structures • This chapter begins a new path in our programming ability • Basically we can cause our programs to follow different paths, react differently to different situations. • It’s an exciting time to be learning Java programming
Chapter Overview • Control structures • Boolean expressions • If statements • Nested if • Switch • Looping
Section 4.1 Control structures • Sequence • Selection • Alter normally sequential flow of a program • Repetition • Alter normally sequential flow of a program
Boolean Expressions • Boolean has two possible values • True • False • Simplest Boolean expression is variable • boolean leapYear = true; • Can only be assigned true or false
Relational operators • < less than • <= less than or equal • == equal • > greater than • >= greater than or equal • != not equal
Reading Boolean data • Use JOptionPane.showConfirmDialog(null, “Is this fun?”); • This is the result of the statement • Returns 0 for yes, 1 for no, 2 for cancel
Using the result • To convert this value to boolean simply use the result like this: • boolean myBool = (returnNum == 0) • See methods top of page 186 for method to handle this
Operands • Operands can be: • Literals • Variables
Boolean Operators • && and • || or • ! not
Boolean Operators • (salary < minimumSalary) || (dependents > 5) • (temperature > 90.0) && (humidity > 0.90)
Boolean variables in expressions • winningRecord && (!onProbation)
Boolean Assignment • variable = expression • same = true; • same = (x == y);
Short-circuit • Short circuit evaluation • Stops evaluating as soon as knows the outcome. • Can cause problems depending on what is in statement
Writing Conditions • (min <= x) && (x <= max) x min max
Comparing Characters • ‘c’ < ‘d’ true • ‘a’ > ‘A’ true • ‘3’ > ‘4’ false
Comparing Strings • Must use String methods • string1.equals(string2)
Lexicographic Comparison • string1.compareTo(string2) • Negative value if string 1 < string 2 • Value 0 if string 1 = string 2 • Positive value if string 1 > string 2 • See table pg 195
gross > 100.00 net = gross - tax net = gross Section 4.3 if statement if (gross > 100.00) net = gross – tax; //if expression is true else net = gross; //if expression is false true false
One selection if (x != 0.0) product = product * x;
Syntax single selection • if (condition) statement;
Syntax 2 alternatives if (condition) statement; else statement;
Look at web example • http://faculty.juniata.edu/thomas/cs110/ifelse/Page1.htm
If and compound statements • Use the braces to create a block of code in the if statement. if (x > y) { temp = x; x = y; y = temp; } //end if
If else and compound • See example top page 200
Returning booleans from methods • Look at example 4.8 page 201 • good way • need not do as shown on the bottom of the page
5.5 Decision steps in Algorithms • Decision step: selects one of several actions. • Review example 4.13 Pages 204-205
Case Study page 205 • Payroll problem • Analysis • Design • Implementation • Page 213 variable scope • Local • Data fields
4.5 nested ifs • Besides using the Boolean operators && || and ! We can also create nested if statements. • Nested if statements are often more efficient than a sequence of if statements
if (x > 0) y = y + 1; if (x < 0) y = y – 1; if (x ==0) y = y + 2; if (x> 0) y = y + 1; else if (x < 0) y = y – 1; else //btw x is 0 y = y + 2; Sequence versus Nested
Matching else with If • You must use indentiation to make it clear how your if/else match. • BUT!! The compiler ignores the white space • Java matches each else with it’s closest preceding if that is not already matched with an else
Good or Bad if (x > 0) y = y * 4; if (x < 0) y = y * - 4; else y = y + 4;
Multiple alternative format if (score >= 90) displayResult(“A”); else if (score >= 80) displayResult(“B”); else if (score >= 70) displayResult(“C”); . .
Example • Order matters big time see page 220 • Review tax example page 221
Tips • Code nested ifs one statement at a time. • Code outer if then the internal ifs • TEST TEST TEST
Switch statement • Switch allows you to select from several alternatives. • Works especially well when based on the value of one variable
This is what it looks like switch (editOp) { case 0: search(); break; case 1: insert(); break; case 2: delete(); break; case 3: replace(); break; case 4: displayResult("All done"); break; default: displayResult("Invalid operation."); }
Rules • The switch selector must be an ordinal data type. • Primitive • All values maybe listed • int, boolean, char • Not double • Break causes control to pass to statement after the switch. • Break statements are not always necessary
Another example switch (month) { case 12 : julian = julian + day; case 11 : if (month == 11) julian = julian + day; else julian = julian + 30; case 10 : if (month == 10) julian = julian + day; else julian = julian + 31; case 9 : if (month == 9) julian = julian + day; else julian = julian + 30; case 1 : if (month == 1) julian = julian + day; else julian = julian + 31; }//end switch Case 8 – 2 go in here, slides just aren’t big enough
Returning a value • Use of a return in a switch case statement also stops execution of the statement. • I am a little fussy with entry level programmers having multiple exit points in a method, although will allow it in a switch statement.
Repetition Structures • In the programs we have written each line only executes at most 1 time. • There are times that we want statements to execute multiple times. • When would you want this? • Repetition is 3rd type of control structure • Sequence, selection, repetition
Overview • Loops • Counting loops • Sentinel controlled loops • Flag controlled loops • Menu driven loops • Loop types • while • for • do-while
Counting loops • Loop, repetition of steps in a program. • Counting loop repeats a predetermined number of times. • Name some real life examples of count controlled loops • Counter-controlled loops are controlled by a variable that keeps track of the number of repetitions performed.
While statement • Syntax: while (condition) statement; • Statement is the body of the loop • Can be compound { } • Condition, continues looping while condition remains true
Example int countTenSum = 1; int tenSum = 0 while (countTenSum < 11) { tenSum = tenSum + countTenSum; countTenSum = countTenSum + 1; }
Example int numberEmp = readInt(“number of employees”); int countEmp = 0; while (countEmp < numberEmp) { //read pay data computer gross and net //add one to counter countEmp = countEmp + 1; }
Syntax and formatting while (repetitionCondition) loopBody • Must use indentation for clarity • As in other cases white space is totally ignored by compiler