In this chapter, you will:

Similar documents
Chapter 4: Control Structures I

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

C++ Programming: From Problem Analysis to Program Design, Third Edition

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection)

CMPT 125: Lecture 4 Conditionals and Loops

Chapter 4 - Notes Control Structures I (Selection)

JAVA OPERATORS GENERAL

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Important Java terminology

Prof. Navrati Saxena TA: Rochak Sachan

Lesson 7 Part 2 Flags

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures

Chapter 4: Control Structures I (Selection)

Flow of Control. Chapter 3 Part 3 The Switch Statement

Conditional Execution

Chapter 3. Selections

Full file at

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Introduction to Programming Using Java (98-388)

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Chapter 3: Operators, Expressions and Type Conversion

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

Following is the general form of a typical decision making structure found in most of the programming languages:

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

Flow of Control. Chapter 3

Flow of Control. Chapter 3

Chapter 3 Selection Statements

Honors Computer Programming 1-2. Chapter 5 Exam Prep

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Topics. Chapter 5. Equality Operators

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Flow Control. Key Notion. Statement Categories. 28-Oct-10

Oct Decision Structures cont d

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

CT 229 Java Syntax Continued

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Flow Control. Boaz Kantor Introduction to Computer Science, Fall semester IDC Herzliya

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

A variable is a name that represents a value. For

Selections. CSE 114, Computer Science 1 Stony Brook University

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Conditional Programming

Expression statements are formed by adding a semicolon to the end of certain types of expressions.

Program Control Flow

Program Control Flow

1. An operation in which an overall value is computed incrementally, often using a loop.

Object-Oriented Programming

Research Group. 2: More types, Methods, Conditionals

The Java language has a wide variety of modifiers, including the following:

Key Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions

Operators. Java operators are classified into three categories:

IEEE Floating-Point Representation 1

Java Coding 2. Decisions, decisions!

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Computer Applications Answer Key Class IX December 2017

CS Week 5. Jim Williams, PhD

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Example: Monte Carlo Simulation 1

Flow Control. CSC215 Lecture

Java Basic Programming Constructs

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

Building Java Programs

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Repetition, Looping. While Loop

CSC 1214: Object-Oriented Programming

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

5. Selection: If and Switch Controls

The Arithmetic Operators

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Recognize the correct ordering of decisions in multiple branches Program simple and complex decision

Operators in java Operator operands.

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

H212 Introduction to Software Systems Honors

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

CS 231 Data Structures and Algorithms Fall Event Based Programming Lecture 06 - September 17, Prof. Zadia Codabux

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS

Program Fundamentals

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Java is an objet-oriented programming language providing features that support

For that purpose, java provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

NoSuchElementException 5. Name of the Exception that occurs when you try to read past the end of the input data in a file.

CONDITIONAL EXECUTION

Chapter 4 Control Structures

Transcription:

Java Programming: Guided Learning with Early Objects Chapter 4 Control Structures I: Selection In this chapter, you will: Make decisions with the if and if else structures Use compound statements in an if or if else structure Nest if and if else statements Use AND and OR operators Use the switch statement Understand precedence Use the conditional and NOT operators Introduction : Four ways a computer processes statements: Sequentially Selection Repetition Method calls Branching: alter execution flow by selection Looping: alter execution flow by repetition 1

Relational Operators Express conditions Make comparisons to make decisions Logical (Boolean) expression: has a value of either true or false Relational operator: allows comparisons in a program Relational operators are binary Binary operators require two operands Result of comparison is true or false 2

Expression Meaning Value 8 < 15 8 less than 15 True 6!= 6 6 not equal to 6 False 2.5 > 5.8 2.5 greater than 5.8 False 5.9 <= 7.5 5.9 less than or equal to 7.5 True Comparing Floating-Point Numbers for Equality Check absolute value of difference of two floating-point numbers Difference less than given tolerance Use method abs from class Math Example: Math.abs(x y) < 0.000001 Comparing Characters Expression using relational operators evaluates to true or false based on collating sequence Example: R > T 3

4

Example :- public class LogicalOperators { public static void main(string[] args) { boolean found = true; boolean flag = false; double x = 5.2, num1=2567.58,num2=2567.58; double y = 3.4; int a = 5; int b = 8; int n = 20; char ch = 'B'; System.out.println("!found evaluates to " +!found); System.out.println("x > 4.0 evaluates to " + (x > 4.0)); System.out.println("!found && (x >= 0) evaluates to " + (!found && (x >= 0))); System.out.println("!(found && (x >= 0)) evaluates to " +!(found && (x >= 0))); System.out.println("x + y <= 20.5 evaluates to " + (x + y <= 20.5)); System.out.println("(n >= 0) && (n <= 100) evaluates to " + ((n >= 0) && (n <= 100))); System.out.println("('A' <= ch && ch <= 'Z') evaluates to " + ('A' <= ch && ch <= 'Z')); System.out.println("(a + 2 <= b) &&!flag evaluates to " + ((a + 2 <= b) &&!flag)); System.out.println("num1 = " + num1 + ", num2 = " + num2); System.out.println("The value of " + "num1.equals(num2) is " + num1.equals(num2)); System.out.println("The value of " + "num1 == num2 is " + (num1 == num2)); 5

Comparing Strings Strings compared character by character Comparison continues until: o Mismatch found o Last characters compared and are equal o One string exhausted Shorter string less than larger string if comparison equal through shorter string Use method compareto of class String Strings, the Assignment Operator, and the Operator new Example 1: String str1 = Hello ; String str2 = Hello ; (str1 == str2) evaluates to true str1.equals(str2) evaluates to true Example 2: String str3 = new String( Hello ); String str4 = new String( Hello ); (str3 == str4) evaluates to false str3.equals(str4) evaluates to true 6

Wrapper Classes (Revisited) Use method compareto to compare values of two Integer objects Use method equals to compare values of two Integer objects for equality Relational operators compare values of Integer and Double objects o Using autoboxing and auto-unboxing Assignment operator always uses operator new to create Double object Logical (Boolean) Operators and Logical Expressions Logical (Boolean) operators enable you to combine logical expressions Logical operators take logical values as operands Binary operators: && and Unary operator:! Logical Operators :- Logical Operator Meaning Evaluates Both conditions must be true for the && AND entire condition to be true OR Either condition or both conditions must be true for the entire condition to be true! NOT Reverse the truth condition 7

Logical Operators Table ( and && ) Logical Operators Table ( or ) 8

Relational Operators :- Relational Operator Condition Example < Less Than ( age < 25 ) <= Less Than or Equal ( age <= 25 ) > Greater Than ( age > 25 ) >= Greater Than or Equal ( age >= 25 ) = = Equal ( age = = 25 )!= Not Equal (! ( age < 25 ) ) Operator Precedence for Operators used Operations have higher and lower precedences Expression might contain arithmetic, relational, and logical operators Relational and logical operators evaluated left to right Left-to-right associativity The order in which you use operators makes a difference You can always use parentheses to change precedence or make your intentions clear Precedence Symbols Highest * / % + - > >= < <= = =!= &&? : Lowest = Abbreviated version of if.. else 9

Short-Circuit Evaluation Logical expressions evaluated using efficient algorithm Short-circuit evaluation: o Logical expression evaluated left to right o Stops when value of entire expression known boolean Data Type and Logical (Boolean) Expressions boolean data type has values true and false Logical expressions manipulated using boolean data type boolean, true, false are reserved words 10

Example :- public class StringComparison { public static void main(string[] args) { String str1 = "Hello"; String str2 = "Hi"; String str3 = "Air"; String str4 = "Bill"; String str5 = "Bigger"; System.out.println("Line 10: " + "str1.compareto(str2) evaluates to " + str1.compareto(str2)); System.out.println("Line 11: " + "str1.compareto(\"hen\") evaluates to " + str1.compareto("hen")); System.out.println("Line 12: " + "str4.compareto(str3) evaluates to " + str4.compareto(str3)); System.out.println("Line 13: " + "str1.compareto(\"hello\") evaluates to " + str1.compareto("hello")); System.out.println("Line 14: " + "str2.compareto(\"hi\") evaluates to " + str2.compareto("hi")); System.out.println("Line 15: " + "str4.compareto(\"billy\") evaluates to " + str4.compareto("billy")); System.out.println("Line 16: " + "str5.compareto(\"big\") evaluates to " + str5.compareto("big")); 11

Making Decisions with the if and if else Structures Making a decision involves choosing between alternate courses of action based on some value within a program The value the decision is based on is always Boolean-true or false You can use if or if else statements to make a decision Single alternative- You only perform an action based on one alternative True 12

Example :- public class onlyif { import java.util.*; static Scanner console = new Scanner(System.in); public static void main(string[] args) throws Exception{ char evtype; String eventtype ; System.out.println("This Example To illustrate IF... statement"); System.out.println("Enter Type of Event You Are Scheduling"); System.out.println("Enter C For Coperate Event "); eventtype = console.next(); ;(0)charAt.eventType =evtype if ( evtype == C ) { System.out.println("The Manager Of This Event Will be Carmen Daisy"); System.out.println("\n\nThis Part will always be printed"); Dual alternative Requires two options for a course of action Provides the mechanism for performing one action when a Boolean expression evaluates as true and if it evaluates to false a different action occurs False True 13

Example import java.util.*; public class ifelse { static Scanner console = new Scanner(System.in); public static void main(string[] args) throws Exception{ char evtype; String eventtype ; System.out.println("This Example To illustrate IF... else statement"); System.out.println("Enter Type of Event You Are Scheduling"); System.out.println("Enter C For Coperate Event "); System.out.println("Enter P For Private Event"); eventtype = console.next(); evtype = eventtype.charat(0); System.out.print("The Manager Of This Event Will be "); if (evtype == C ) { System.out.println("Carmen Daisy "); else { System.out.println("Other than Carmen Daisy"); 14

Using Compound Statements in an if or if else Structure To execute more than one statement that depends on the evaluation of a Boolean expression, use a pair of curly braces to place the dependent statements within a block Example :- import java.util.*; public class ifelsecompound { static Scanner console = new Scanner(System.in); public static void main(string[] args) throws Exception{ char evtype; String eventtype ; System.out.println("This Example TO illustrate COMPUND IF.. else statement"); System.out.println("Enter Type of Event You Are Scheduling"); System.out.println("Enter C For Coperate Event "); eventtype = console.next(); evtype = eventtype.charat(0); if (evtype== C ) { System.out.print("The Manager Of This Event Will be "); System.out.println(" Carmen Daisy "); else if (evtype == D ) { System.out.print("The Manager Of This Event Will be "); System.out.println(" Don Showla"); 15

Nesting if and if else statements Nesting if and if else statements- Statements with an if inside another if Nested if statements are useful when two conditions must be met before some action can occur Example :- public class NestedIF { public static void main(string[] args) throws Exception { // int intemp; int intemp = 20; if ( intemp > 32 ) { if ( intemp > 80 ) { System.out.println("It is very Hot"); else { System.out.println("It is Moderate"); else { System.out.println("It is Freezing"); 16

Using the Switch Statement Switch statement- To test a single variable against a series of exact integer or character values The switch statement uses four keywords switch- starts the structure and is followed immediately by a test expression enclosed in parentheses case- is followed by one of the possible values for the test expression and a colon break- optionally terminates a switch structure at the end of each case default- optionally is used prior to any action that should occur if the test variable does not match any case Example :- public class casestatement { public static void main (String[] args) { int num = 3; System.out.println("Integer Driven"); switch(num) { case 1 : System.out.println("Number is 1"); break; case 2 : System.out.println("Number is 2"); break; case 3 : System.out.print("Number is 3, It is the "); System.out.println("Third Sutition "); break; default: System.out.println("Other number"); System.out.println("Character Driven"); char ayear='f'; switch (ayear){ case 'F': System.out.println("Freshman"); break; case 'S': System.out.println("Sophomore"); System.out.println("Yes, the 2nd year."); break; case 'T' : System.out.println("Junior"); break; case 'L': System.out.println("Senior"); break; default: System.out.println("Invalid year"); System.out.println("Program Ends"); What happens if one omits break????? 17

Examples If ( tickets > 3 age < 25 && gender = = 'M' ) If ( ( tickets > 3 age < 25 ) && gender = = 'M' ) Precedence Symbols Highest * / % + - > >= < <= = =!= &&? : Lowest = Abbreviated version of if.. else Using the Conditional and NOT Operators Conditional operator- Requires three expressions separated with a question mark and a colon Is used as an abbreviated version of the if else structure testexpression? true Result : false Result SmallNum = ( a < b )? a : b; 18

Using the Conditional and NOT Operators NOT operator- To negate the result of any Boolean expression Written as the explanation point (!) If (! ( age < 25 ) ) { p = 125; else { p = 200; 19

Key Terms action statement A statement that follows a condition in a selection statement. boolean expression Another name for a logical expression. boolean values The values true and false. branch A selection or choice. branching Altering the flow of program execution by making a selection or choice. condition Another name for the logical expression in a selection statement. conditional expression A statement written with the conditional operator. conditional operator Another way to write an if else statement; written as? :. logical expression An expression that has a value of either true or false. logical values The values true and false. loop A structure that allows a program to execute a statement over and over. looping Altering the flow of program execution by repetition of statements. method calls Using a method inside of anther method. pairing an else with an if In a nested if statement, Java associates an else with the most recent incomplete if. postcondition A statement specifying what is true after the method call is completed. precondition A statement specifying the conditions that must be true before the method is called. relational operator An operator that allows you to make comparisons in a program. repetition The program repeats particular statements a certain number of times, depending on one or more conditions. sequential One after the other; one of the four ways a program can process statements. short-circuit evaluation A process in which the computer evaluates a logical expression from left to right and stops as soon as the value of the expression is determined. ternary operator An operator that takes three arguments. 20