Chapter 3 Flow of Control Chapter 3 Branching Loops exit(n) method Boolean data type and expressions Java: an Introduction to Computer Science & Programming - Walter Savitch 1 What is “Flow of Control”? Flow of Control is the execution order of instructions in a program All programs can be written with three control flow elements: 1. Sequence - just go to the next instruction 2. Selection - a choice of at least two – either go to the next instruction – or jump to some other instruction 3. Repetition - a loop (repeat a block of code) at the end of the loop – either go back and repeat the block of code – or continue with the next instruction after the block Selection and Repetition are called Branching since these are branch points in Java: an Introduction to Computer Science & Programming - Walter Savitch the flow of control Chapter 3 2 Simple Selection - if Example … // some code before this … change = 0; if(amountTendered > amountDue) // change is due (begin body of the if statement) change = amountTendered – amountDue; // (end body of the if statement) System.out.println(“Change to be given back “ + change); // always runs Chapter 3 Test / comparison / condition is inside ( ) ‘s If the test evaluates (returns) to true, then the body is executed (otherwise they do not) Statements after the body of the if statement always execute Java: an Introduction to Computer Science & Programming - Walter Savitch 4 Java if statement syntax Chapter 3 Syntax: if (Boolean_Expression) Action if true;//execute only if true next action;//always executed Note the indentation for readability (not compile or execution correctness) Java: an Introduction to Computer Science & Programming - Walter Savitch 5 Java Statement Blocks: Compound Statements Action if true can be either a single Java statement or a set of statements enclosed in curly brackets (a compound statement, or block) All statements between For example: braces are controlled by if if(change > 0) { // determine coins to give back (begin body) quarters = change / 25; int amountLeft = change % 25; dimes = amountLeft / 10; … } // end if System.out.println(“Returning change of “ + change + “\n using “ + quarters + “quarters” Chapter Java: an Introduction to Computer Science & Programming - Walter Savitch …3 6 Two-way Selection - if-else Example Select either one of two options, depending on test value … // price is determined; taxability is determined if (taxable == ‘y’) { tax = price * TAXRATE; } else { tax = 0; } total = price + tax; Curly braces are NOT necessary if only one statement BUT I always use them Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 7 Two-way Selection: if-else Syntax Chapter 3 Syntax: if (Boolean_Expression) { Action1 //execute only if true } else { Action2//execute only if false } Action3//always executed Java: an Introduction to Computer Science & Programming - Walter Savitch 8 OK – Let’s Solve a Problem Chapter 3 Tickets for the Olympic Downhill Ski race are $100 each. If you buy 10 or more, then there is a service charge of $100. If you buy fewer, the service charge is $15 per ticket. Write a program to handle the I/O and calculations – displaying total cost. Java: an Introduction to Computer Science & Programming - Walter Savitch 9 Definition of Boolean Values With if’s, we have seen that which branch is taken depends on a test condition which evaluates to either true or false Variables (or expressions) that are either true or false are called boolean variables (or expressions) Hence the syntax was written as if (Boolean_Expression) The test for the if is a boolean expression – a part of a statement that evaluates to (returns) either true or false boolean is a primitive data type in Java Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 10 Boolean Expressions Chapter 3 Often two values are compared For example: Is amountTendered less than amountDue? Is taxable equal to ‘y’ ? Is numberOfTix greater than or equal to 10? etc. Values being compared can be any data type (or class), but they should be the same data type (or class) Java: an Introduction to Computer Science & Programming - Walter Savitch 11 Java Comparison Operators Math Notation Name = equal to not equal to > greater than Java Java Notation Examples == balance == 0 answer = 'y' != income tax answer != 'y' > income > outgo greater than or equal to >= points >= 60 < less than < pressure < max less than or equal to <= income <= outgo Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 12 What about a range? Chapter 3 Sometimes we want to know whether a value is within a range (e.g. is a test score between 80 and 90?) Knowing mathematics, we’d like to write this as if (80 < testScore < 90) { … But alas … this is not how things work with computers Instead if ( ( testScore >80) && (testScore < 90) ) { … AND (&&) is a logical operator. Something AND somethingelse evaluates to true if both components evaluate to true Java: an Introduction to Computer Science & Programming - Walter Savitch 13 Compound Boolean Expressions Chapter 3 Use && to AND two or more conditions Use || to OR two or more conditions – if either component is true then the whole expression is true For example, if ( (gpa < 0.0) || (gpa > 4.0) ) { … In this example the parentheses are not required but are added for clarity » See text (and later slides) for Precedence rules » Note the short-circuit, or lazy, evaluation rules in text (and later in slides) » Use a single & for AND and a single | for OR to avoid short-circuit evaluation and force complete evaluation of a boolean expression Java: an Introduction to Computer Science & Programming - Walter Savitch 14 NOT ! Chapter 3 NOT essentially reverses Indicated with ! if ( ! ( x > 0) ) { … Usually you can do without NOT Java: an Introduction to Computer Science & Programming - Walter Savitch 15 Java Comparison Methods for String Class Chapter 3 “==“ does not do what you may think for String objects » When “==“ is used to test objects (such as String objects) it tests to see if the storage addresses of the two objects are the same – are they stored in the same location? – more will be said about this later Use “.equals” method to test if the strings, themselves, are equal String s1 = “What are you doing?”; String s2; s2 = SavitchIn.readLine(); //s1.equals(s2) returns true if the user enters What are you doing?, false otherwise .equals()is case sensitive Use .equalsIgnoreCase()to ignore case Java: an Introduction to Computer Science & Programming - Walter Savitch 16 Nested If’s Chapter 3 An IF-Else statement can have any kind of statement(s) inside the if or inside the else This includes another IF if (numCredits >= 12) { if (resident == ‘y’) { totalCost = … } else { totalCost = … } else { … Java: an Introduction to Computer Science & Programming - Walter Savitch 17 if-else if-else if-…-else Example Chapter 3 Can have if statements nested inside else too if(score >= 90) grade = ‘A’); else if (score >= 80) grade = ‘B’; else if (score >= 70) grade = ‘C’; else if (score >= 60) grade = ‘D’; else grade = ‘F’; Java: an Introduction to Computer Science & Programming - Walter Savitch 18 Multibranch selection: if-else if-else if-…-else One way to handle situations with more than two possibilities Syntax: if(Boolean_Expression_1) Action_1 else if(Boolean_Expression_2) Action_2 . . . else if(Boolean_Expression_n) Action_n else Default_Action Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 19 switch Example An alternative way of doing a multibranch selection switch(seatLocationCode) { case 1: System.out.println(“Orchestra”); price = 40.00; break; case 2: System.out.println(“Mezzanine”); price = 30.00; break; case 3: System.out.println(“Balcony”); price = 15.00; break; default: System.out.println(“Unknown seat code”); break; } Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 20 Multibranch selection Syntax: switch break may be omitted IF appropriate for your algorithm (it usually is NOT appropriate) switch(Controlling_Expression) { case Case_Label: Can be any number of statements cases like this one. … break; case Case_Label: statements … break; } Chapter 3 default: statements … break; Default case is optional. Java: an Introduction to Computer Science & Programming - Walter Savitch 21 Multibranch selection: switch Chapter 3 Controlling_Expression must be char, int, short or byte Controlling Expression and Case_Label must be same type When a break statement is encountered, control goes to the first statement after the switch. Java: an Introduction to Computer Science & Programming - Walter Savitch 22 Repetition: Loops Chapter 3 Structure: » Usually some initialization code » body of loop » loop termination condition Several logical organizations » counting loops » sentinel-controlled loops » infinite loops » minimum of zero or minimum of one iteration Several programming statement variations » while » do-while » for Java: an Introduction to Computer Science & Programming - Walter Savitch 23 while : a counting loop example Chapter 3 A loop to sum 10 numbers entered by user int next; //Loop initialization int count = 1; int total =0; while(count <= 10) //Loop termination condition { //Body of loop next = SavitchIn.readLineInt(); total = total + next; count++; //Loop termination counter } Java: an Introduction to Computer Science & Programming - Walter Savitch 24 while: a sentinel controlled loop example Chapter 3 A loop to sum positive integers entered by the user next is the sentinel The loop terminates when the user enters a negative number //Initialization int next = 0; int total = 0; while(next >= 0) //Termination condition { //Body total = total + next; next = SavitchIn.readLineInt(); } Java: an Introduction to Computer Science & Programming - Walter Savitch 25 while Loop Chapter 3 Syntax: while(Boolean_Expression) { //body of loop First_Statement; ... Last_Statement; } Something in body of loop should eventually cause Boolean_Expression to be false. Initialization statements usually precede the loop. Boolean_Expression is the loop termination condition. May be either counting or sentinel loop » Good choice for sentinel loop Java: an Introduction to Computer Science & Programming - Walter Savitch 26 while: A Minimum of Zero Iterations Because the first input value read and the test precedes the loop, the body the while loop body may not execute at all //Initialization int next; int total = 0; next = SavitchIn.readLineInt(); while(next >= 0)//Termination condition { //Body total = total + next; next = SavitchIn.readLineInt(); } Chapter 3 If the first number the user enters is negative the loop body never executes Java: an Introduction to Computer Science & Programming - Walter Savitch 27 OK – Let’s Solve another Problem Chapter 3 Calculate the GPA for a student – ask continually if there are more classes to consider. For each class, ask for the grade (A,B,C,D, or F) and the number of credits. Display the student’s GPA. Java: an Introduction to Computer Science & Programming - Walter Savitch 28 Do code for GPA? Pseudocode totalPoints = 0 totalCredits = 0 While more courses ask for and get grade ask for and get # credit hours Figure # points (A – 4, B – 3, C - 2, D – 1, F – 0) current course points = points * credit hours add current course points to totalPoints add one to totalCredits ENDWHILE Gpa = totalPoints / totalCredits Display GPA Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 29 Another Task Involving Loops Calculate yx (assume x is an integer) … // declare, ask for, and get y and x … int count = 1; double total = y; while (count < x) { total = total * y; count++; } // display result Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 30 Another Task Involving Loops Ensuring valid inputs (e.g. making sure # hours worked is between 1 and 60) System.out.println(“How many hours?”); double numHours = SavitchIn.readLineDouble(); while ((numHours < 1) || ( numHours > 60) { System.out.println(“I’m sorry, you have entered an invalid number of hours”); System.out.println(“Please re-enter a number between 1 and 60”); numHours = SavitchIn.readLineDouble(); } Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 31 Another Task Involving Loops Find the average score on a quiz Pseudocode Initialize total to 0 Initialize counter to 0 Ask for and get how many numbers While counter < number of numbers ask for and get next score add score to total add one to counter If counter > 0 set ave to total / counter print the average Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 32 do-while Example int count = 1; int number = 10; do //Display integers 1 - 10 on one line { System.out.println(count + “ “ ); count++; }while(count <= number); Note System.out.print() is used and not System.out.println() so the numbers will all be on one line Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 33 do-while Loop Chapter 3 Syntax do Something in body of loop { //body of loop should eventually cause Boolean_Expression to First_Statement; be false. ... Last_Statement; } while(Boolean_Expression); Note Semicolon Initialization code may precede loop body Loop test is after loop body so the body must execute at least once (minimum of at least one iteration) May be to Compare While!! either counting or sentinel loop » One Good choice for sentinel loop Java: an Introduction to Computer Science & Programming - Walter Savitch 34 for Loop Good choice for counting (counter-controlled) loop Initialization, loop test, and loop counter change are part of the syntax Syntax: for(Initialization; Boolean_Expression; Update_Action) loop body; Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 35 for Example Count up from 1 to 5 for(int count = 1; count <= 5; count++) { System.out.println(count + " "); } (only need {}’s if more than one statement in body) Don’t put a semicolon after the ) – you’ll end the loop right there – no body!! Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 36 for Loop for(Initialization; Boolean_Expression; Update_Action) loop body; Execution sequence: 1. Initialization - executes only once, before the loop body is executed the first time 2. Boolean_Expression - the loop test 3. loop body - execute only if loop test is true 4. Update_Action - typically changes the loop counter 5. Boolean_Expression - Repeat the loop test (step 2), etc. Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 37 for Flowchart Chapter 3 <draw on board> Java: an Introduction to Computer Science & Programming - Walter Savitch 38 Any for Could be done with a while Initialization; while (Boolean_Expression) { loop body; Update_Action; } int count = 1; while (count <= 5) { System.out.println(count + " "); count++; } Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 39 for Loop is THE Loop to use for Counter-Controlled Repetition If you know when writing the program how many times loop will need to go around If the program will know how many times loop will need to go around by the time we get to the loop the first time Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 40 Example where “program knows…” … Calculate yx (assume x is an integer) // declare, ask for, and get y and x … double total = y; for (int count = 1; count < x; count++) { total = total * y; } // display result Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 41 BTW Increment can be down, something more than 1 for (int cnt = 10; cnt > 0; cnt--){ … for (int cnt = 0; cnt < 10; cnt = cnt + 2) { … Expressions are optional (e.g. no initialization (leaving others off would be weird) int cnt = 0; for ( ; cnt < 10; cnt++) { … Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 42 BTW Chapter 3 Use of control variable inside loop Displaying – legal and often done Use in calculation – legal and sometimes done e.g. sq = cnt * cnt; Changing – legal but generally not a good idea Java: an Introduction to Computer Science & Programming - Walter Savitch 43 Let’s Do A Problem Calculate n! int total = 1; for (int cnt = 1; cnt < n; cnt++) { total = total * cnt; } System.out.println(n + “! equals: “ + total); Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 44 Nested for for loops, like while loops and other control structures, can be nested inside each other for (int tens = 1; tens <= 2; tens++) { for (int ones = 0; ones < 10; ones++) { System.out.println(“ “ + tens + ones); } } <Walkthrough> Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 45 Some more about designing for loops If loop design isn’t coming naturally … » You can write pseudocode without a loop and look for a repeating pattern Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 46 Some Practical Considerations When Using Loops The most common loop errors are unintended infinite loops and off-by-one errors in counting loops Sooner or later everyone writes an unintentional infinite loop » To get out of an unintended infinite loop enter ^C (control-C) Off-by-one – loop goes around one too many or one too few times Another problem – testing for == or != with double / float Loops should tested thoroughly, especially at the boundaries of the loop test, to check for off-by-one and other possible errors Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 47 Tracing a Variable in a Loop Tracing a variable: print out the variable each time through the loop – gathering evidence to capture bug A common technique to test loop counters and troubleshoot off-by-one and other loop errors Can insert temporary output statements to print values. Modern systems provide a built-in tracing system that allows you to trace a variable without having to change your program (We will talk about soon) Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 48 Java Flow Control Statements Sequence the default Java automatically executes the next instruction unless you use a branching statement Chapter 3 Branching: Selection if if-else if-else if-else if- … - else switch Branching: Repetition while do-while for Java: an Introduction to Computer Science & Programming - Walter Savitch 49 break Statement Chapter 3 As with in switch, break takes you out of loop Any kind of loop – while, for, do-while Example in display 3.13 on p176 Makes loop harder to understand Use sparingly Java: an Introduction to Computer Science & Programming - Walter Savitch 50 The exit Method If you have a program situation where it is pointless to continue execution you can terminate the program with the exit(n) method n is often used to identify if the program ended normally or abnormally n is conventionally 0 for normal termination and non-zero for abnormal termination We did this in our GUI programs System.exit(0); In that case because the program was really done – to end GUI controls Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 51 The Type boolean A primitive type Can have expressions, values, constants, and variables just as with any other primitive type Only two values: true and false Can use a boolean variable as the condition in an if statement if (classIsFull) System.out.println(“Please Choose Another Class.”); else … // register Using a boolean variable as the condition can make an if statement easier to read by avoiding a complicated expression. Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 53 Truth Tables for boolean Operators && (and) Value of A Value of B || (or) A && B A || B true true true true true true true false false true false true false true false false true true false false false false false false ! (not) Chapter 3 Value of A Value of B Value of A !A true false false true Java: an Introduction to Computer Science & Programming - Walter Savitch 55 Precedence Rules Revisited Highest Precedence ( )’s override all precedence rules First: the unary operators: +, -, ++, --, and ! (right to left) Second: the binary arithmetic operators: *, /, % Third: the binary arithmetic operators: +, Fourth: the boolean operators: <, >, =<, >= Fifth: the boolean operators: ==, != Sixth: the boolean operator & Seventh: the boolean operator | Eighth: the boolean operator && Ninth: the boolean operator || Lowest Precedence Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 57 Revisiting Short-Circuit Evaluation Short-circuit evaluation—only evaluating as much of a boolean expression as necessary. Example: if ((assign > 0) && ((total/assign) > 80)) System.out.println(“Good work”); else System.out.println(“Work harder.”); If assign > 0 is false, then the complete expression cannot be true because AND is only true if both operands are true. Java will not evaluate the second part of the expression. Here Short-circuit evaluation prevents a divide-by-zero exception when assign is 0. Chapter 3 Java: an Introduction to Computer Science & Programming - Walter Savitch 58