Download presentation
Presentation is loading. Please wait.
Published byRosamond Hart Modified over 8 years ago
1
Lecture 4: Introduction to Control Flow Statements and Reading User Input Michael Hsu CSULA
2
Notes on Lab 2 For the final percentage, just add up the percentages of each category, no need to divide by 100 Don’t use a calculator to do the math, use Java math operators Why bother writing a program if you’re going do it by hand?
3
Recall from lectures 3 and 3-1 Variables Data types Declaring and initializing variables Operators Augmented operators Pre/post increment/decrement
4
4 Relational Operators
5
Control Flow Statements Your source code is usually executed from top to bottom In the order that they appear Control Flow Statements Breaks up your execution order Conditionally execute particular blocks of code Some categories: Decision making If-then, if-then-else, switch Looping for, while, do-while Branching Break, continue return Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html
6
if-then statements Most basic of all control flow statements A programmer's wife tells her: "Go to the store and get a loaf of bread. If they have eggs, get a dozen." The programmer comes home with 12 loaves of bread. Tells your program to execute a certain section of code only if a particular test evaluates to true Syntax: if(TEST){ //Do stuff in here is TEST evaluates to true }
7
if-then example Example: boolean isThisClassCS201Section3 = true; if(isThisClassCS201Section3){ System.out.println("My dog lectures better than the instructor"); System.out.println("JK, please don't give me a bad grade :)"); } Eclipse tells you if the code block is “dead code”, never can be reached
8
Omitting the Braces of an if-then Statements If only one statement inside the then clause, then you can omit the braces: if (isThisClassCS201Section3) System.out.println("My dog lectures better than the instructor"); However, I do not recommend doing this, as it can lead to unexpected errors: What if you add another statement in the then clause? What if you have a bunch of if-then statements nested?
9
if-then-else Statement Provides a secondary path of execution when an “if” clause evaluates to false. Example: boolean isThisClassCS201Section3 = true; if (isThisClassCS201Section3) { System.out.println("My dog lectures better than the instructor"); } else { System.out.println("I'm not gonna joke about the instructor cause he/she probably can't take the joke"); } You can also omit braces for the else clause if there is just one statement
10
if-else if - else You can use else if, with or without a final else: if(condition 1) { // statements to execute if condition 1 is true } else if(condition 2) { // statements to execute if condition 1 is false but condition 2 is true } // can use any number of else if blocks else { // statements to execute if condition none of the conditions are true }
11
11 if – else if – else Flowchart
12
Nesting if-else statements if(condition 1) { // statements execute if condition 1 is true if (condition 2){ // statements execute if condition 1 and condition 2 are both true } else { // statements execute if condition 1 is true but condition 2 is false } else{ // statements execute if condition 1 is false }
13
13 Note The else clause matches the most recent if clause in the same block.
14
14 Note, cont. Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k) System.out.println("A"); } else System.out.println("B"); This statement prints B.
15
15 Common Errors Adding a semicolon at the end of an if clause is a common mistake. if (radius >= 0); { area = radius*radius*PI; System.out.println( "The area for the circle of radius " + radius + " is " + area); } This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. This error often occurs when you use the next-line block style. Wrong
16
16 TIP
17
17 CAUTION
18
A Note on Naming Conventions for Boolean variables The identifier of a boolean variable should be a phrase/sentence that is either true or false Examples: isNumberEven isOver9000 hasBeenNoticedBySenpai
19
19 Logical Operators OperatorName Description !notlogical negation &&andlogical conjunction ||orlogical disjunction ^exclusive orlogical exclusion
20
20 Truth Table for Operator ! p!p Example (assume age = 24, weight = 140) truefalse!(age > 18) is false, because (age > 18) is true. falsetrue !(weight == 150) is true, because (weight == 150) is false.
21
21 Truth Table for Operator && p1p1 p2p2 p 1 && p 2 Example (assume age = 24, weight = 140) false (age 18) and (weight <= 140) are both false. falsetruefalse truefalse (age > 18) && (weight > 140) is false, because (weight > 140) is false. true (age > 18) && (weight >= 140) is true, because both (age > 18) and (weight >= 140) are true.
22
22 Truth Table for Operator || p1p1 p2p2 p 1 || p 2 Example (assume age = 24, weihgt = 140) false true (age > 34) || (weight 34) is false, but (weight <= 140) is true. truefalse true (age > 14) || (weight >= 150) is false, because (age > 14) is true. true
23
23 Truth Table for Operator ^ p1p1 p2p2 p 1 ^ p 2 Example (assume age = 24, weight = 140) false (age > 34) ^ (weight > 140) is true, because (age > 34) is false and (weight > 140) is false. falsetrue (age > 34) ^ (weight >= 140) is true, because (age > 34) is false but (weight >= 140) is true. truefalse true (age > 14) ^ (weight > 140) is true, because (age > 14) is true and (weight > 140) is false. true false
24
24 Example Problem: Body Mass Index Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your weight in kilograms and dividing by the square of your height in meters. The interpretation of BMI for people 16 years or older is as follows:
25
25 switch Statements switch (status) { case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; break; case 2: compute taxes for married file separately; break; case 3: compute taxes for head of household; break; default: System.out.println("Errors: invalid status"); System.exit(1); }
26
26 switch Statement Flow Chart
27
27 switch Statement Rules switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for-default; } The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. The value1,..., and valueN must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch- expression. Note that value1,..., and valueN are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x.
28
28 switch Statement Rules The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed. switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for-default; } The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression. When the value in a case statement matches the value of the switch-expression, the statements starting from this case are executed until either a break statement or the end of the switch statement is reached.
29
Best Practices for switch statements: ALWAYS include breaks for each case It can get very, very confusing
30
30 Trace switch statement switch (day) { case 1: case 2: case 3: case 4: case 5: System.out.println("Weekday"); break; case 0: case 6: System.out.println("Weekend"); } Suppose day is 2: animation
31
31 Trace switch statement switch (day) { case 1: case 2: case 3: case 4: case 5: System.out.println("Weekday"); break; case 0: case 6: System.out.println("Weekend"); } Match case 2 animation
32
32 Trace switch statement switch (day) { case 1: case 2: case 3: case 4: case 5: System.out.println("Weekday"); break; case 0: case 6: System.out.println("Weekend"); } Fall through case 3 animation
33
33 Trace switch statement switch (day) { case 1: case 2: case 3: case 4: case 5: System.out.println("Weekday"); break; case 0: case 6: System.out.println("Weekend"); } Fall through case 4 animation
34
34 Trace switch statement switch (day) { case 1: case 2: case 3: case 4: case 5: System.out.println("Weekday"); break; case 0: case 6: System.out.println("Weekend"); } Fall through case 5 animation
35
35 Trace switch statement switch (day) { case 1: case 2: case 3: case 4: case 5: System.out.println("Weekday"); break; case 0: case 6: System.out.println("Weekend"); } Encounter break animation
36
36 Trace switch statement switch (day) { case 1: case 2: case 3: case 4: case 5: System.out.println("Weekday"); break; case 0: case 6: System.out.println("Weekend"); } Exit the statement animation
37
37 Conditional Expressions if (x > 0) y = 1 else y = -1; is equivalent to y = (x > 0) ? 1 : -1; (boolean-expression) ? expression1 : expression2 Ternary operator Binary operator Unary operator
38
38 Conditional Operator if (num % 2 == 0) System.out.println(num + “is even”); else System.out.println(num + “is odd”); System.out.println( (num % 2 == 0)? num + “is even” : num + “is odd”);
39
39 Conditional Operator, cont. boolean-expression ? exp1 : exp2
40
40 Operator Precedence var++, var-- +, - (Unary plus and minus), ++var, --var (type) Casting ! (Not) *, /, % (Multiplication, division, and remainder) +, - (Binary addition and subtraction) , >= (Relational operators) ==, !=; (Equality) ^ (Exclusive OR) && (Conditional AND) Short-circuit AND || (Conditional OR) Short-circuit OR =, +=, -=, *=, /=, %= (Assignment operator)
41
Reading User Input We normally use GUI (graphical user interfaces) to get data from User Popup windows, text fields, etc. In school, we often use command line input from keyboard for simplicity sake
42
java.util.Scanner Lets you get input from keyboard (System.in) to make the programs more fun Couple of things to notice You have to import the scanner class because it is not under java.lang You don’t need to import java.lang.Math cause the compiler does it for you Import before you declare the class Import statement: import java.util.Scanner; Difference between classes, object, and instance java.util.Scanner is a class A class is like a blueprint/template. To make copies of it that do different things, we need to create an object An object is an instance of its class
43
How to Use java.util.Scanner 1. import java.util.Scanner; 2. Create an instance of the Scanner class, a Scanner object: Scanner scanner = new Scanner(System.in); //We set up Scanner object with the name “scanner” 3. Do Stuff with it 4. Close it to free up resources: scanner.close();
44
Scanner Input Methods https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html Since most of the the methods are instance methods, you have to create the scanner object before you can use it The main method is not an instance method because of the keyword “static” For example, methods in String and Math are static methods You can read an entire line, a String, a double, an int, etc. Read the documentation and lecture code examples to learn more about Scanner methods
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.