Lecture 4: Introduction to Control Flow Statements and Reading User Input Michael Hsu CSULA.

Slides:



Advertisements
Similar presentations
L5:CSC © Dr. Basheer M. Nasef Lecture #5 By Dr. Basheer M. Nasef.
Advertisements

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4: Selections.
Control Structures Corresponds with Chapters 3 and 4.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 3 Control Statements.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Introduction to Java Programming, 4E Y. Daniel Liang.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 3 Control Statements.
Chapter 3 Selections Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Control Statements.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
The switch Statement, DecimalFormat, and Introduction to Looping
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
INF120 Basics in JAVA Programming AUBG, COS dept Lecture 05 Title: Decision/Selection Control Structures Reference: MalikFarrell, chap 1, Liang Ch 3.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.1 Chapter 3 Selections.
John Hurley Cal State LA CS 201 Lecture 4. If If statements do just what you expect test whether a condition is true and if so, execute some statements.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Information  HW1 now available  Group Project (Find your group members)  Start thinking about group projects.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Introduction to Control Statements JavaScript – Part 3 George Mason University June 3, 2010.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. CHAPTER 3: SELECTIONS 1.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
1 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
Chapter 3 Selection Statements §3.1 The Boolean Type and Operators §3.2 The if-else Statements §3.3 Case Studies §3.4 Logical Operators §3.5 Switch Statements.
1 Chapter 5 Control Statements. 2 Objectives F To understand the flow of control in selection and loop statements. F To use Boolean expressions to control.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
Introduction to Control Statements IT108 George Mason University.
John Hurley Spring 2011 Cal State LA CS 201 Lecture 5:
Chapter 3 Selections Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved
Chapter 4 Selections © Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Group Project (Find your group members)
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 3 Selections Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.
Chapter 3 Selections Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 3 Control Statements
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Selections Java.
The switch Statement, and Introduction to Looping
CHAPTER 4 Selection CSEG1003 Introduction to Computing
Lecture 3- Decision Structures
Chapter 3 Selections ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH Introduction to Java Programming, Liang (Pearson 2014)
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 5 Control Statements
Chapter 3 Selections Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Chapter 3 Control Statements
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
Lecture Notes – Week 2 Lecture-2
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 3 Selections Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1.
Presentation transcript:

Lecture 4: Introduction to Control Flow Statements and Reading User Input Michael Hsu CSULA

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?

Recall from lectures 3 and 3-1  Variables  Data types  Declaring and initializing variables  Operators  Augmented operators  Pre/post increment/decrement

4 Relational Operators

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:

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 }

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

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?

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

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 if – else if – else Flowchart

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 Note The else clause matches the most recent if clause in the same block.

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 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 TIP

17 CAUTION

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 Logical Operators OperatorName Description !notlogical negation &&andlogical conjunction ||orlogical disjunction ^exclusive orlogical exclusion

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 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 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 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 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 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 switch Statement Flow Chart

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 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.

Best Practices for switch statements:  ALWAYS include breaks for each case  It can get very, very confusing

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 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 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 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 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 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 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 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 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 Conditional Operator, cont. boolean-expression ? exp1 : exp2

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)

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

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

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();

Scanner Input Methods   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