DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

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

Text Input and Conditionals

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

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

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

Decision Making in C

The following expression causes a divide by zero error:

(I m not printing out these notes! Take your own.)

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Chapter 4: Making Decisions

Chapter 4: Making Decisions

Python for Informatics

5. Control Statements

Conditional Programming

3 The L oop Control Structure

Relational Operators and if. Class 10

5. Selection: If and Switch Controls

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

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

Software Design & Programming I

LESSON 3. In this lesson you will learn about the conditional and looping constructs that allow you to control the flow of a PHP script.

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

Decision Structures. Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

SELECTION. (Chapter 2)

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Boolean Expressions. Is Equal and Is Not Equal

LECTURE 04 MAKING DECISIONS

Boolean Expressions. Is Equal and Is Not Equal

Mr G s Java Jive. #11: Formatting Numbers

Pace University. Fundamental Concepts of CS121 1

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Relational Operators EXAMPLE. C++ By

Flow Control. CSC215 Lecture

Programming Lecture 4

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Decision Structures. Lesson 03 MIT 11053, Fundamentals of Programming

IT 1033: Fundamentals of Programming Loops

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

CS112 Lecture: Repetition Statements

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Key Differences Between Python and Java

CS125 : Introduction to Computer Science. Lecture Notes #6 Compound Statements, Scope, and Advanced Conditionals

Introduction to Bioinformatics

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

EECS 183. Week 3 - Diana Gage. www-personal.umich.edu/ ~drgage

Module 2: Choice and Iteration

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Programming Lecture 4

CS 106 Introduction to Computer Science I

Chapter 2, Part III Arithmetic Operators and Decision Making

CPS122 Lecture: From Python to Java

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

COMP 202 Java in one week

DECISION MAKING STATEMENTS

Chapter 8. Statement-Level Control Structures

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Full file at

Boolean Logic & Branching Lab Conditional Tests

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Introduction. C provides two styles of flow control:

CS112 Lecture: Making Choices

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Making Decisions In Python

Chapter 3. Selections

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

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Flow Control: Branches and loops

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

Selection Statements. Pseudocode

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Create your first workbook

BRANCHING if-else statements

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

(Refer Slide Time 6:48)

Decision Making -Branching. Class Incharge: S. Sasirekha

Flow Control. So Far: Writing simple statements that get executed one after another.

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Control Structures: if and while A C S L E C T U R E 4

Table of Contents. Lesson Topics Page Lab Summary Page

Lecture 10: for, do, and switch

8. Control statements

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Conditionals & Loops /

Chapter 4 - Notes Control Structures I (Selection)

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Full file at C How to Program, 6/e Multiple Choice Test Bank

CS 115 Lecture 8. Selection: the if statement. Neil Moore

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

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

Lecture 6. Statements

Transcription:

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA S o far all the programs we have created run straight through from start to finish, without making any decisions along the way. Many times, however, you may need to execute a different set of code based on criteria input by the user. Just as you might say to yourself, If she doesn t call me, I am not going to speak to her again, a computer program uses decision structures to decide what actions to take depending on certain conditions. The decision structure Java programmers use to perform this type of conditional logic are called if statements. All if statements use boolean expressions to determine whether to execute or skip a statement (or a block of statements). A boolean experession is a Java expression that, when evaluated, returns a boolean value that is, either true or false. Boolean expressions often compare the value of a variable with the value of some other variable, a literal, or perhaps a simple arithmetic expression through the user of something called a relational operator. RELATIONAL OPERATORS Java evaluates a boolean expression by first evaluating the expression on the left, then evaluating the expression on the right, and finally applying the relational operator to determine if the entire expression evaluates to true or false. The equal sign (==), for example, is a relational operator that compares the value of the expression to the left, with the value of the expression to the right. It always returns a TRUE or FALSE value. if (score == 0) The following are six (6) Java relational operators that are used to evaluate boolean expressions: OPERATOR NAME DESCRIPTION EXAMPLE < Less than Returns true if the expression on the left evaluates to a value that is less than the value of the expression on the right. if (score < 100) <= Less than or equal Returns true if the expression on the left evaluates to a value that is less than or equal to the value of the expression on the right. if (score <= 100) == Equal Returns true if the expression on the left evaluates to a value that is equal to the value of the expression on the right. if (score == 100) MAKING DECISIONS: Using If Statements in Java Page 1 of 8

!= Not equal Returns true if the expression on the left does not equal the value of the expression on the right. if (score!= 100) >= Greater than or equal Returns true if the expression on the left evaluates to a value that is greater than or equal to the value of the expression on the right. if (score >= 100) > Greater than Returns true if the expression on the left evaluates to a value that is greater than the value of the expression on the right. if (score > 100) Note that the relational operator that tests for equality is two equal signs in a row (==). A single equal sign is the assignment operator. So if you try to use a single equal sign in a boolean expression you will get a compile-time error. THE if STATEMENT In its most basic form, an if statement lets you execute a single statement or a block of statements only if a boolean expression returns true. The following is the basic form of the if statement: if (boolean-expression) statement Note that the boolean expression must be enclosed in parentheses. Also, if you use only a single statement, it must end with a semicolon. But the statement can also be a statement enclosed by braces. In that case, each statement within the block needs a semicolon, but the block itself doesn t. Here s an example of a typical if statement: double hourlyrate = 10; In this example, a variable named hourlyrate is initialized to 8.00, and then set to 10.00 if hoursworked is greater than 40. So what will hourlyrate be equal to if hoursworked is not greater than 40. If you answered 8.00, you re correct! Indenting the statement under the if statement is customary to make the structure of your code more obvious. It isn t necessary, but always a good idea. Here s an example that uses a block rather than a single statement: double MAKING DECISIONS: Using If Statements in Java Page 2 of 8

hourlyrate = 10; totalpay = hoursworked * hourlyrate; In the above example, the two statements within the braces are executed if hoursworked is greater than 40. Otherwise, neither statement is executed. Keep in mind that indentation by itself doesn t create a block. For example, consider this example: double hourlyrate = 10; totalpay = hoursworked * hourlyrate; In the above example, I didn t use the braces to mark a block, but indented the last statement as if it were part of the if statement. This will result in the last statement being executed whether or not the expression in the if statement returns true. It might be a good idea to always code if statements using statement blocks regardless of the number of statements that conditionally execute, as the following example illustrates: hourlyrate = 10; The reason why this would not be a bad idea is because it makes the structure of your code a little more obvious by adding extra white space around the statement. Also, if you later decide you need to add a few statements to the block, the braces are already there. THE if- STATEMENT Unlike an if statement which executes an instruction(s) if the conditional expression returns true, an if statement includes an optional clause that is executed if the conditional expression returns false. The basic format of an if- statement is: if (boolean-expression) statement statement Here s an example that uses an if- statement to determine one s hourly rate: double hourlyrate; MAKING DECISIONS: Using If Statements in Java Page 3 of 8

In this example, the hourlyrate is set to 10.00 if the hoursworked is greater than 40. If the hoursworked is not greater than 40, then the hourlyrate is set to 8.00. You can, of course, write the above statement using blocks as follows: double hourlyrate; NESTED if STATEMENTS The statement that goes in the if or part of an if- statement can be any kind of Java statement, including another if or -if statement. This is called NESTING, and an if or if- statement that includes another if or -if statement is called a NESTED IF STATEMENT. The general form of a nested if statement is as follows: if (expression1) if (expression2) statement1 statement2 if (expression3) statement3 statement4 In this example, expression1 is first evaluated. If it returns true, expression2 is evaluated. If that expression is true, statement1 is executed; otherwise statement2 is executed. But if expression1 is false, then expression3 is evaluated. If expression3 is true, statement3 is executed; otherwise statement4 is executed. Suppose I have two classes of employees: part-timers and full-timers and they get a different hourly rate based on the number of hours they work. I could implement a pay structure with a nested if statement as follows: MAKING DECISIONS: Using If Statements in Java Page 4 of 8

if (parttime == true) hourlyrate = 12.00; OR if (parttime == true) hourlyrate = 12.00; This example assumes that if the parttime variable isn t true, then the employee must be a full-time employee. In the above example, what would be my hourly rate if I was a full-time employee who worked a total of 40 hours? If you said 12.00, you are correct! THE if- if STATEMENT A common pattern for nested if statements is to have a series of if- if statements: The general format of an if- if statement is as follows: MAKING DECISIONS: Using If Statements in Java Page 5 of 8

if (expression1) statement1 if (expression2) statement2 if (expression3) statement3 For example, suppose I want to assign four different hourly rates based on the amount of hours worked. I can easily implement a series of if- if statements to assign different rates by doing the following: if (hoursworked > 30) hourlyrate = 12.00; if (hoursworked > 20) It is important to keep in mind that your boolean expression must be properly ordered because statements are executed for the first true condition only, and skips all the other conditions. For example, if I had changed the sequence of my statements to look like this, what would the hourly rate be for an employee who works 60 hours? if (hoursworked > 0) if (hoursworked > 20) if (hoursworked > 30) hourlyrate = 12.00; If you said 8.00, you re correct! These if statements sets the hourlyrate to 8.00 because the boolean expression in the first statement always returns true (assuming the hoursworked variable isn t zero or negative), thus resulting in the other if statements never being evaluated. THE switch STATEMENT The switch statement is sometimes useful when you need to select one of several alternatives based on the value of an integer or character type variable. The following is the basic form of a switch statement: switch (expression) case constant1: statements; break; MAKING DECISIONS: Using If Statements in Java Page 6 of 8

case constant2: statements; break; case constant3: statements; break; default: statements; break; You can code as many case groups as you want or need. Each begins with the word case followed by a constant (usually a simple numeric literal) and a colon. Then you code one or more statements that you want executed if the value of the switch expression equals the constant. The last line of each case group is a break statement, which causes the entire switch statement to end. The default group, which is optional, is like a catch-all case group. Its statements are executed only if none of the previous case constants match the switch expression (very similar to an statement). BOOLEAN OPERATORS Sometimes we may want our program to perform an action if more than one condition (logical AND) or one of multiple conditions is true (logical OR). For example, I may want to set an employee s hourly rate to 14.00 if he/she is a full-time employee and works more than 40 hours a week. In this case we need to use a BOOLEAN OPERATOR. Boolean operators let you combine two or more conditions in the same expression. if (fulltime == true && hoursworked > 40) The following are Boolean operators that can be used to form more complex Boolean expressions: OPERATOR LOGIC BOOLEAN EXAMPLE && Both conditions must be true Either condition must be true! Result of the condition is reversed AND if (fulltime == true && hoursworked > 40) OR if (fulltime == true hoursworked > 40) NOT if!(hoursworked > 40) MAKING DECISIONS: Using If Statements in Java Page 7 of 8

^ One and only one of the conditions is true XOR if (fulltime == true ^ hoursworked > 40) ILLUSTRATING BOOLEAN EXPRESSIONS WITH TRUTH TABLES How a compound Boolean expression evaluates with && and operators can be illustrated with TRUTH TABLES. Truth tables show the possible outcomes of compound Boolean expressions. AND (&&) A B RESULT True True True True False False False True False False False False OR ( ) A B RESULT True True True True False True False True True False False False XOR (^) A B RESULT True True False True False True False True True False False False A True False NOT (!) RESULT False True MAKING DECISIONS: Using If Statements in Java Page 8 of 8