Download presentation
Presentation is loading. Please wait.
Published byΑνδρόνικα Γεωργιάδης Modified over 6 years ago
1
Java Programming Control Structures Part 1
Phil Tayco San Jose City College Slide version 1.0 September 25, 2018
2
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 isActive; isActive = true;
3
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 isActive 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”
4
Relational Expressions
System.out.println(“Enter your age:”); int age = input.nextInt(); 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
5
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
6
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” If “x != y” results in false and a certain course of action, you could also use “x == y” the do the same course but only if the exression resulted in true Choice of expression depends on the logic you want to use to make it easier to understand the code
7
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”);
8
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”);
9
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”);
10
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”);
11
Control Structures There are 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
12
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
13
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?
14
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 it 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
15
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”);
16
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, practice!
17
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
18
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”);
19
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
20
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
21
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”);
22
Control Structures It may appear the code prints the results you expect, but only if you test for age values less than 21 (only “Not an adult” will appear) If you do an age value of 21, that also works, but note 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) 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)
23
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 to make sure the logic meets your coding requirements Practice, practice, practice!
24
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”);
25
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?
26
Boolean Operators In the logic world, the evaluation of possible values is often captured in a “truth table” This shows both sides of the && operation must be true to result in an overall value of true && true false
27
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 using this expects only one true or false value – the individual relational expression evaluations are part of the puzzle
28
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”);
29
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?
30
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 Use of Boolean operators is good, but recognize the logic to design your code appropriately
31
Boolean Operators The other popular Boolean operator is “||” which is the logical OR The difference with || from && is that if either side is (or both sides are) true, the overall expression is true || true false
32
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”);
33
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
34
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
35
Combining Operators What is this code logically trying to do?
if (number % 2 == 0) System.out.println(“Even”); else System.out.println(“Odd”);
36
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 a precedence of operators 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 must be an int to work with 2 (also int) For ==, the result of the % operation is an int and is compared with 0 (also int)
37
Combining Operators Why is this wrong?
if (age >= 12 && age < 20) System.out.println(“Teen”); else System.out.println(“Not a teen”);
38
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 in the next discussion module 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 good because the test the “edge” of your relational expression logic
39
Programming Exercise 2 Write a program that asks the user for the lengths of 3 sides of a triangle and prints whether or not those sides make a valid triangle The rule for determining if a triangle is valid from the lengths of 3 sides is that the sum of the lengths of any two sides of a triangle is greater than the length of the third side The program must prompt and ask the user for the length of each side. Read each number in as a double data type Based on the triangle validity rule, if the given lengths make a valid triangle, print “Valid” If the given lengths do not make a valid triangle, print “Invalid” followed by printing which 2 sides did not add up to being greater than the 3 side
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.