Java Programming Control Structures Part 3 Phil Tayco

  • Slides: 22
Download presentation
Java Programming Control Structures Part 3 Phil Tayco San Jose City College Slide version

Java Programming Control Structures Part 3 Phil Tayco San Jose City College Slide version 1. 1 March 23, 2021

Advanced Control Structures • Now that we have reviewed the fundamentals of selection (if…else)

Advanced Control Structures • Now that we have reviewed the fundamentals of selection (if…else) and repetition programming structures (loops), we can explore some advanced programming capabilities within them • We’ll look at more ways to control a basic loop • We’ll then look at ways to code specific types of multiple if…else selection structures • In the Java online text, this covers us through most of chapter 3 up to and including section 3. 6

Break and Continue • Sometimes it is necessary to end a loop completely while

Break and Continue • Sometimes it is necessary to end a loop completely while going through an iteration • Here’s a variation of the average calculation loop boolean keep. Going = true; double total = 0. 0; int counter = 0; Scanner input = new Scanner(System. in); while (keep. Going) { System. out. print(“Enter number or 0 to stop: “); double number = input. next. Double(); if (number == 0) keep. Going = false; else { total += number; counter++; } } System. out. printf(“Average is %. 2 fn”, total / counter);

Break and Continue • It’s not foolproof, but it works for the most part

Break and Continue • It’s not foolproof, but it works for the most part • Notice the use of the boolean variable “keep. Going” • On the first line, we are treating keep. Going like any other variable • Since keep. Going is a Boolean, it can only have a value of true or false • In the while loop condition, notice we do not test if it is equal to anything (such as “keep. Going == true”) • This is not necessary because the requirement for the test condition is that it be a boolean value • Since keep. Going already is a Boolean, we can just use its value straight up • This style is often viewed as improved readability of code boolean keep. Going = true; double total = 0. 0; int counter = 0; Scanner input = new Scanner(System. in); while (keep. Going)

Break and Continue • Notice also the use of System. out. print • This

Break and Continue • Notice also the use of System. out. print • This is like println except it does not go to the next line after the String is printed on the screen • This is for presentation style and can be used as you prefer with other println and printf code • The effect here is that the cursor appears on the same line as the prompt • When the user enters their data, they will complete it by hitting Enter which, in effect, puts the cursor on the next line while (keep. Going) { System. out. print(“Enter number or 0 to stop: “); double number = input. next. Double();

Break and Continue • The if statement in the loop body is what controls

Break and Continue • The if statement in the loop body is what controls the loop • If the user enters 0 for their number, the keep. Going boolean variable is set to false and nothing else occurs in the loop • When keep. Going is re-evaluated, since its value is false, the loop ends while (keep. Going) { System. out. print(“Enter number or 0 to stop: “); double number = input. next. Double(); if (number == 0) keep. Going = false; else {

Break and Continue • In this example, an if statement in the loop body

Break and Continue • In this example, an if statement in the loop body controls the repetition • In such cases, it can be useful to use a “break” statement instead • The following code has the same effect as the previous code example - note the differences double total = 0. 0; int counter = 0; Scanner input = new Scanner(System. in); while (true) { System. out. print(“Enter number or 0 to stop: “); double number = input. next. Double(); if (number == 0) break; total += number; counter++; } System. out. printf(“Average is %. 2 fn”, total / counter);

Break and Continue • The “keep. Going” variable is now gone and the loop

Break and Continue • The “keep. Going” variable is now gone and the loop condition is fixed to a value of true • This means every time the while condition is evaluated, it will always see true and keep doing the loop body • This appears to be an infinite loop, but the if statement takes care of that • When the user enters 0, the if condition will evaluate true • The “break” means to exit the body of code the statement is in – since the break is part of the if statement, the body of code that will be exited is the while loop body • Here, the break effectively ends the loop double total = 0. 0; int counter = 0; Scanner input = new Scanner(System. in); while (true) { System. out. print(“Enter number or 0 to stop: “); double number = input. next. Double(); if (number == 0) break;

Break and Continue • Notice also that there is no else clause for the

Break and Continue • Notice also that there is no else clause for the if • Technically, this means no matter whether or not the if condition resolves true or false, the code after it executes as normal sequence • In this case, though, when the if resolves to true, the break is executed which effectively ends the loop (making the rest of the loop body code not execute) • The code indirectly acts as an else and is a code pattern that comes up often while (true) { System. out. print(“Enter number or 0 to stop: “); double number = input. next. Double(); if (number == 0) break; total += number; counter++; }

Break and Continue • Another form of loop management variation is “continue” for (int

Break and Continue • Another form of loop management variation is “continue” for (int c = 1; c <= 25; c++) { if (c % 3 != 0) continue; System. out. printf (“Number divisible by 3: %dn”, c); } • In this simple example, the for loop counts from 1 to 25 • For each number, it checks to see if it is divisible by 3 and if so, prints it out • However, the loop body code is written differently – If the number is not divisible by 3, continue the loop – Otherwise print out that the number is divisible by 3

Break and Continue • “continue; ” is the same as break in that when

Break and Continue • “continue; ” is the same as break in that when it is reached, it stops the remaining part of the body of code from executing • Unlike break, continue must be used in a loop body (break can be used in other code bodies as we will see later) • Continue also doesn’t exit the loop – instead, it goes to the evaluation step of the loop and retests – In the for loop example, c++ is also performed • Thus, it is possible with the use of continue to keep the loop going • This is useful in loop designs where the entire loop body does not necessarily have to be executed each time • Use of break and continue can be useful in your programming exercise 4

Switch • Observe the following code: Scanner input = new Scanner(System. in); System. out.

Switch • Observe the following code: Scanner input = new Scanner(System. in); System. out. print(“Enter choice: “); int choice = input. next. Int(); if (choice == 1) // Execute code for choice 1 else if (choice == 2) // Execute code for choice 2 else if (choice == 3) // Execute code for choice 3 else // Execute code for all other choice values • This is a straightforward selection statement based on the choice value entered by the user • Logically, this is correct usage of if…else • There are patterns in the code here that commonly occur in programs for which Java provides an alternate form of coding style

Switch Scanner input = new Scanner(System. in); System. out. print(“Enter choice: “); int choice

Switch Scanner input = new Scanner(System. in); System. out. print(“Enter choice: “); int choice = input. next. Int(); if (choice == 1) // Execute code for choice 1 else if (choice == 2) // Execute code for choice 2 else if (choice == 3) // Execute code for choice 3 else // Execute code for all other choice values • In the selection statement, all possible outcomes are dependent on testing one variable (choice) • With each test of choice, it is compared to a specific value • When these 2 characteristics are true with an if…else statement, a “switch” statement can be used instead

Switch Scanner input = new Scanner(System. in); System. out. print(“Enter choice: “); int choice

Switch Scanner input = new Scanner(System. in); System. out. print(“Enter choice: “); int choice = input. next. Int(); switch (choice) { case 1: // Execute code for choice 1 break; case 2: // Execute code for choice 2 break; case 3: // Execute code for choice 3 break; default: // Execute code for all other choice values } • The switch statement functions exactly the same as the if…else statement previously coded

Switch int choice = input. next. Int(); switch (choice) • The switch statement contains

Switch int choice = input. next. Int(); switch (choice) • The switch statement contains a block of code that begins executing a sequence of code where the case value equals the switch variable value • You can read this switch as “if choice equals any of the following…” • “choice” must be a variable that is either an int, char, or enumeration (enum we will discuss later) • These data types can only be used with a switch because they tend to be used for testing for specific sets of values • Strings and doubles have a very high amount of variability (“h”, “him”, etc. or 2. 01, 2. 011) • Only 1 variable can be tested with a switch

Switch { case 1: // Execute code for choice 1 break; case 2: //

Switch { case 1: // Execute code for choice 1 break; case 2: // Execute code for choice 2 break; • The individual cases represent code to begin execution when the switch variable equals the case value • “case 1” is equivalent to “if (choice == 1)” • The code for it is executed as normal – note that there are no curly braces for the case • This is important because any case code to execute is not considered to be in a block

Switch { case 1: // Execute code for choice 1 break; case 2: //

Switch { case 1: // Execute code for choice 1 break; case 2: // Execute code for choice 2 break; • For example, let’s say choice’s value was 2 • Case 2 would be the starting point for the code in the switch block • All code from there is executed to the end of the switch block • This is where the “break” statements become important • What would happen if choice was 1 and the case 1 code did not have a break?

Switch { case 1: // Execute code for choice 1 case 2: // Execute

Switch { case 1: // Execute code for choice 1 case 2: // Execute code for choice 2 break; • Because the case represents the starting point of code in a switch block, all code from there must be treated as a sequence within the block • The rest of the case indicators are ignored • Result is the code above in red is all executed for case 1 • As we saw earlier, “break” means to exit the block of code you are in • That rule applies here for switch blocks • Rule of thumb: Put a “break” first with every case

Switch case 3: // Execute code for choice 3 break; default: // Execute code

Switch case 3: // Execute code for choice 3 break; default: // Execute code for all other choice values } • The last “case” is known as the “default” • This is the point within the switch block where the code execution begins after all other cases are checked • It is the equivalent to the “else” clause in an “if…else” statement • Note there is no “break” statement needed at the end of the default case – it is not necessary because if the default is executed, there will be no code to break from after it (i. e. you’re at the end of the switch block)

Switch case 3: case 4: case 5: // Execute code for choices 3, 4,

Switch case 3: case 4: case 5: // Execute code for choices 3, 4, and 5 break; default: // Execute code for all other choice values } • Here, a range of switch values is tested • This is the equivalent of “if (choice == 3 || choice == 4 || choice == 5)” – You can think of it as choice >= 3 and choice <= 5, but case statements are often better to think of as starting points for specific values • If choice is either 3, 4, or 5, the search within the switch would reach one of those case lines and execute code from there as normal

Switch • Switch statements are generally considered to be the preferred style of code

Switch • Switch statements are generally considered to be the preferred style of code when the opportunity is there • The logical equivalent using if…else can always be done instead and ultimately becomes a matter of style • Switch can only be used in situations where you are testing 1 variable for specific values • Typical uses are for handling selections from a menu or performing actions based on different types of data read • If you have a wide range of possible values to consider, it will likely be better to go with an if statement

Programming Exercise 5 • Go back to your solution for Programming Exercise 4 and

Programming Exercise 5 • Go back to your solution for Programming Exercise 4 and update it to use a switch statement to handle the main menu • In addition, find a way to use either the break and/or continue statement in one or more of your loops in your Exercise 4 solution • If you already did these for your exercises, make sure I see it so I can mark credit appropriately