Java Programming Control Structures Part 1 Phil Tayco









































- Slides: 41

Java Programming Control Structures Part 1 Phil Tayco San Jose City College Slide version 1. 1 February 11, 2020

Boolean Data Types • In the previous module, we introduced primitive data types such as “int” and “double” • Another data type fundamental primitive data type is “boolean” • A boolean variable has either a value of true or false boolean is. Active; is. Active = true;

Boolean Data Types • boolean values can be used reliably because they can only have one of two possible values • boolean variables can be directly assigned a value like the is. Active variable • They can also be a value that is the result of some operation • For example, say you have an integer variable used to represent age • If we check to see if the age value is greater than or equal to 21, there will only be 2 results of that comparison – it either is true or not • We can do this in code using a “relational operator”

Relational Expressions System. out. println(“Enter your age: ”); int age = input. next. Int(); System. out. println(age >= 21); • The first 2 lines prompt the user to enter an integer representing an age and stores the value entered in the age variable (this code assumes you’ve already created an input Scanner variable) • On the third line, “age >= 21” is an expression using the relational operator “>=“ • “>=“ represents “greater than or equal to” • Depending on the age value entered, the result of checking “age >= 21” will be a boolean value (the result of the comparison will either be true or false) – here, that value then gets printed

Relational Expressions • The “age >= 21” code is known as a “relational expression” • Relational expressions use relational operators between 2 values and result in a boolean value of either true or false • Use of the resulting boolean value is very powerful for control structures • Like the assignment and arithmetic operators, relational operators first compare data types on both sides of the expression to ensure they are compatible • “age >= 21” means first check 21’s data type (int) and age’s data type (also an int) – if they are compatible, the operation continues

Relational Operators • There are 6 relational operators commonly used – – – “>=“: greater than or equal to “>”: greater than “<=“: less than or equal to “<”: less than “!=“: not equal to “==“: equal to • The equality operator needs to use 2 equal signs because 1 equal sign is the assignment operator • Use of an appropriate matter can be arbitrary as long as the logical intent is captured correctly – “x > 21” for integers can also be “x >= 22” – “x != y” is the opposite logical expression of “x == y” – Choice of expression depends on the logic you want to use to make it easier to understand the code

Control Structures • This leads to code that can use relational expressions to decide which statements to execute based on the result • Below is an “if…else statement” which is very frequently used in programming languages if (age >= 21) { System. out. println(“Adult”); } else { System. out. println(“Not an adult”); } System. out. println(“Done”);

Control Structures • “if” is followed by parentheses and does not end with a “; ” • The code in the parentheses must result in a boolean value – often this is a relational expression if (age >= 21) { System. out. println(“Adult”); } else { System. out. println(“Not an adult”); } System. out. println(“Done”);

Control Structures • If the Boolean value in the parentheses is true, the block of code that immediately follows is executed • The block of code in the “else” part is skipped and the code after the entire if…else statement is executed next if (age >= 21) { System. out. println(“Adult”); } else { System. out. println(“Not an adult”); } System. out. println(“Done”);

Control Structures • If the boolean value in the parentheses is false, the code in the “else” block is executed next and then followed by the code after it if (age >= 21) { System. out. println(“Adult”); } else { System. out. println(“Not an adult”); } System. out. println(“Done”);

Control Structures • There a few observations to make with the logic of the if…else statement • The code that is executed based on the result of the relational expression is going to be one block or the other block – it is not possible to print “Adult” and “Not an adult” • The code after the if…else statement is always reached – whether “Adult” or “Not an adult” is printed, “Done” will always follow • There is no “; ” on the “if” line and “else” line – this is because “; ” represents end of statement and in those lines, our logical thought is not yet complete • There are many variations on coding with if statements

Control Structures • if with no else: if (age >= 21) { System. out. println(“Adult”); } System. out. println(“Done”); • This will check if age >= 21 and if so, print “Adult” and that’s it • “Done” will always be printed regardless • This approach is used if you only want to test if one specific situation is true – if it’s false, we don’t do anything about it

Control Structures • Back to back if statements: if (age >= 21) { System. out. println(“Adult”); } if (age < 21) { System. out. println(“Not an adult”); } System. out. println(“Done”); • This will result in the same logical effect as the “if…else” example • Why would this be considered less efficient?

Control Structures • Remember that the control flow with an if statement is to first evaluate the expression in the parentheses – if it is true, execute the block of code after the “if (…)” • If it is false, go to the else block – if the else block doesn’t exist, the if statement is complete • In this example, the first if statement is evaluated. Once that is done, the second if statement is definitely evaluated • Logically the way it is written, this code sequence will have the same effect as the if…else, but this is less efficient because 2 if statement relational expressions are always evaluated

Control Structures • Blocks of code mean multiple lines can be executed based on the result evaluated: if (age >= 21) { System. out. println(“Adult”); System. out. println(“Thank you for your info”); } else { System. out. println(“Not an adult”); System. out. println(“Thanks for your help”); }

Control Structures • Here, both blocks contain multiple lines of code • The same rules apply in that if the relational expression is true, the block of code after the “if” is executed. Otherwise, the block in the “else” • Any sequence of code that you learn can be in these code blocks • Determining the correct logical combination of statements and control structures is the key to designing programs • The challenge is often determining what relational expressions to use and what code belongs in the blocks • Practice, practice!

Control Structures • If you only have one line of code to execute in a block, you do not need the curly braces if (age >= 21) System. out. println(“Adult”); else { System. out. println(“Not an adult”); System. out. println(“Thanks for your help”); } • Indentation of code is very helpful here to easily visualize which statements are executed when • If in doubt, always use curly braces, but as you get more experienced, using only when necessary is very common

Control Structures • else blocks can continue the if statement: if (age > 21) System. out. println(“Adult”); else if (age < 21) System. out. println(“Not an adult”); else System. out. println(“You are a new adult”); System. out. println(“Done”);

Control Structures • This is considered to be one large if…else statement • If the age is greater than 21, Adult is printed and the rest is skipped down to “Done” • If age is not greater than 21, then the next if statement is evaluated which explicitly checks to see if age is less than 21 • If that is true, Not an adult is printed, then Done • If both those cases are false, then You are a new adult is printed followed by Done

Control Structures • Like before, only one of these 3 cases will be executed based on the relational expression evaluations • Be careful when reviewing/creating such code! • Look at the relational expressions in the parentheses as resulting in true or false – “age > 21” is either true or false – If it’s true, age is 22 or 23 or 24 and so on – If it’s false, age is 21 or 20 or 19 and so on • The rest of the logic here works out correctly, but how would you test this? • A good test is to use values for age that check each “branch” of the if statement – in this case, running it 3 times with values that encounter each code block

Control Structures • What’s wrong here? if (age > 21) System. out. println(“Adult”); if (age < 21) System. out. println(“Not an adult”); else System. out. println(“You are a new adult”); System. out. println(“Done”);

Control Structures • It may appear the code prints the results you expect, but only if you test for age values less than or equal to 21 • Where it breaks down is if you use an age value greater than 21 such as 75 – (age > 21) is true – “Adult” is printed. Good so far! – (age < 21) is definitely evaluated and is false – Because (age < 21) is false, the else associated with it is also executed (You are a new adult is printed as well) • Note that if you do an age value of 21, that also works, but observe the evaluations that occur: – (age > 21) is false – nothing printed there – (age < 21) is definitely evaluated (it does not say “else if”) – this is also false so nothing printed there either – Because (age < 21) is false, the else associated with it is executed (You are a new adult)

Control Structures • These are challenging errors to discover because they are not caught by the compiler • The compiler’s job is to make sure you constructed the code correctly following the language grammar and syntax rules • It cannot evaluate your code and say you might have a logical error in your design • The only way to confirm that is to design appropriate tests that at least cover all the possible outcomes to make sure the logic meets your coding requirements • Practice, practice!

Boolean Operators • Let’s explore more on relational expressions • These expressions are based on testing certain conditions on existing data values • Often, these conditions to check are compounded • What if we wanted to check if age and gender? int age = 25; char gender = ‘M’; if (age > 21) System. out. println(“Adult”); if (gender == ‘M’) System. out. println(“Male”);

Boolean Operators • It is possible to combine the if statements into one check: if (age > 21 && gender == ‘M’) System. out. println(“Adult Male”); • The “&&” is an AND operation and is known as a “Boolean operator” • The data types on either side must be boolean values • After evaluating each boolean value, the && operation results in its own overall boolean value • Given that boolean values are either true or false, how many possible combination of values will the && operator encounter?

Boolean Operators • In the logic world, the evaluation of possible values is often captured in a “truth table” && true false false • This shows both sides of the && operation must be true to result in an overall value of true

Boolean Operators if (age > 21 && gender == ‘M’) System. out. println(“Adult Male”); • “age > 21” is evaluated first – in this example, its value will be true • “gender == ‘M’ is evaluated next – in this example, its value is also true • Since both true values, the overall result is true • Remember that the if statement expects only one true or false value in the parentheses – you can have multiple individual relational expressions joined by Boolean operators but the overall expression must reach true or false

Boolean Operators • What is wrong with the logic here? int age = 25; char gender = ‘F’; if (age > 21 && gender == ‘M’) System. out. println(“Adult Male”); else System. out. println(“Adult Female”);

Boolean Operators • At first, this appears correct, particularly with the test data used: – age > 21 is true – Gender == ‘M’, though, is false – true && false results in overall false • It is important to note now that the exact way to evaluate this is that the overall result value of the relational expression in the parentheses is false • By way of the if…else structure, this means we go to the else block, which prints “Adult Female” • What other test data will show the logic is incorrect?

Boolean Operators int age = 15; char gender = ‘M’; if (age > 21 && gender == ‘M’) System. out. println(“Adult Male”); else System. out. println(“Adult Female”); • Technically, the data here is a male that is not an adult – yet, the result will print Adult Female – gender == ‘M’ is true, but age > 21 is false – false && true results in overall false – Overall false means go to the else block

Boolean Operators • Use of Boolean operators is good, but recognize the logic to design your code appropriately • The testing guideline is to use cases that test all possible outcomes • You should also try to test all the logical ways the outcomes can be reached • The previous if…else statement implies that there are 2 outcomes to test • However, the relational expression contains 2 parts joined by AND • This results in 4 test cases: – – age age = = 25, 20, gender = = ‘M’ -> (correct expected result) ‘M’ -> (incorrect expected result) ‘F’ -> (incorrect expected result)

Boolean Operators • The other popular Boolean operator is “||” which is the logical OR || true false true false • The difference with || from && is that if either side is (or both sides are) true, the overall expression is true

Boolean Operators • Is this correct logic? int age = 15; char gender = ‘F’; if (age > 21 || gender == ‘M’) System. out. println(“Adult Male”); else System. out. println(“Not adult male”);

Boolean Operators • Again, the only way the else block is reached is if the overall relational expression is false • With an ||, both have to be false to get there – age > 21 in this example is false (not an adult) – gender == ‘M’ is also false (not male) – Overall value is then false (not an adult and not male) • So the looks correct, but what about the other case? – If age was 25 (true) but gender is “F” (false), the overall expression is still true, printing Adult Male – If age was 15 (false) but gender is “M” (true), printing Adult Male still occurs – Only if age was 25 AND gender is “M” would printing Adult Male be correct • This again shows the importance of testing all the ways outcomes are reached based on the logical design of your relational expressions

Boolean Operators • Guidelines for using if…else, relational expressions and Boolean operators: • Plan out your logic first before coding, especially if you’ve never previously programmed • Think about what you want the end result possibilities to look like and form the relational expression based on it • Thinks about what test data you’re going to use to ensure your logic meets your expectations • Test all branches of the if…else statement – don’t assume if one set of test data runs the correct block of code, the other block works as expected • Be exhaustive before being fancy – start with simple relational expressions and make sure they work, and then see if using Boolean operators or other logic changes make sense

Combining Operators • What is this code logically trying to do? if (number % 2 == 0) System. out. println(“Even”); else System. out. println(“Odd”);

Combining Operators • This combines an arithmetic operation with a relational and is the classic formula for testing if a number is even or odd • First, divide number by 2 and get the remainder • Compare the remainder against 0 to get a Boolean value of either true or false • Note there is an order of operations occurring (% is done before ==) – a full table is in the text and will be covered when we address all operators • Also note with each operator, the data types are still first evaluated – For %, “number” and the value of 2 are both ints – For ==, the result of the % operation (an int) and is compared with the value of 0 (also int) which will result in an value of either true or false for the if to use

Combining Operators • Why is this wrong? if (age >= 12 && age < 20) System. out. println(“Teen”); else System. out. println(“Not a teen”);

Combining Operators • The logic is set up correctly, but the values are off by one • If age is 13 to 19 integer range, it is correctly saying “Teen” • All other values show “Not a teen” except for 12 • If age equals 12, the overall expression is true resulting in printing “Teen” • This is a classic “off by one” logic error and more often occurs in loop control structures which will be discussed later • This shows the importance of creating good test data – Values like 15, 2 and 25 would work as expected – Values like 12, 13, 19, and 20 are also good because they test the “edge” of your relational expression logic

Programming Exercise 2 • Write a program that asks the user for the lengths of 3 sides of a triangle and prints whether or not these sides make a valid triangle • The rule to use is the “Triangle Inequality Theorem” – search for it on the internet to learn the logic for it • Your program must prompt and ask the user for the length of each side. Read each number in as a double data type

Programming Exercise 2 • Code the logic of theorem such that if the lengths given by the user make a valid triangle, the program prints “These sides make a valid triangle” • If the given lengths do not make a valid triangle, print “These sides do not make a valid triangle” • As with programming exercise 1, do not worry about the user entering incorrect data like words or negative numbers