Introduction to Computer Programming Decisions, Decisions: Boolean Expressions and Selection.

Slides:



Advertisements
Similar presentations
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Advertisements

Introduction to Computer Programming Looping Around Loops I: Counting Loops.
Introduction to Computer Programming Decisions If/Else Booleans.
Scanner Pepper With credits to Dr. Siegfried. The Scanner Class Most programs will need some form of input. At the beginning, all of our input will come.
Introduction to Computer Programming Loops N Decisions If/Else Counting Loops.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: Scanner ; if/else reading: , 4.2, 4.6.
Java Variables and Expressions CSC160 Professor Pepper (presentation adapted from Dr. Siegfried)
Introduction to Computer Programming Looping Around Loops II : Conditional Loops.
Introduction to Computer Programming CSC171 – 001 Getting Started – Chapters 1 & 2 Professor Pepper (presentation adapted from Dr. Siegfried)
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution.
Scanner & Stepwise Refinement Pepper With credit to Dr. Siegfried.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Topic 11 Scanner object, conditional execution Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Computer Science Selection Structures.
Java Programming: From the Ground Up
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
© The McGraw-Hill Companies, 2006 Chapter 2 Selection.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
22/11/ Selection If selection construct.
Introduction Chapter 1 8/31 & 9/1 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Decisions, Decisions, Decisions Conditional Statements In Java.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
CSCI 1226 FALL 2015 MIDTERM #1 REVIEWS.  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice, keyboards,
1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
31/01/ Selection If selection construct.
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
A First Book of C++ Chapter 4 Selection.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Boolean expressions and if-else statements
Building Java Programs
User input We’ve seen how to use the standard output buffer
SELECTION STATEMENTS (1)
Building Java Programs
Control Statement Examples
SELECTION STATEMENTS (2)
Building Java Programs
Introduction to Computer Programming
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Lecture Notes – Week 2 Lecture-2
Chapter 2 Programming Basics.
Building Java Programs
Building Java Programs
CSC 1051 – Data Structures and Algorithms I
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Building Java Programs
Repetition CSC 1051 – Data Structures and Algorithms I Course website:
Presentation transcript:

Introduction to Computer Programming Decisions, Decisions: Boolean Expressions and Selection

What is a decision? A decision involves choosing whether to follow a given course of action, or which one of several different courses of action. We do this countless times during the day, making literally thousands of small decisions. For example, when we reach an intersection, we decide whether to cross it in the following manner: IF the light is green THEN cross the street ELSE wait for the light to change

What is a decision? (continued) IF the light is green THEN cross the street ELSE wait for the light to change This decision has three parts: – the condition –a course of action to follow if the condition is true –a course of action to follow if the condition is false.

The basic structure of decisions There are many decisions that do not have an IF-THEN-ELSE structure. For example, IF there is mail in the mailbox THEN open the mailbox and take it out there is no action to be taken when the condition is false.

The basic structure of decisions (continued) This can be rewritten as: IF there is mail in the mailbox THEN open the mailbox and take it out ELSE do nothing

Choosing From More Than 2 Options There are occasions when we may do one of several different things, depending on some value. Imagine that you are going to the bank, where are several different type of transactions. You may wish to: –make a deposit –cash a check –transfer between accounts –order new checks or – just check your balance.

Choosing From More Than 2 Options (continued) We could write this as: IF you want to make a deposit THEN process deposit ELSE IF you want to cash a check THEN process check ELSE IF you want to transfer money THEN process transfer ELSE IF you want to order checks THEN process order ELSE IF you want to check balance THEN process balance ELSE it must be an error

if and if-else Some problems may have a set of instructions that are only performed under some conditions. These require an if construct. Other problems may have two or more alternative sets of instructions depending on some condition(s). If there are two alternatives, it requires an if-else construct.

if and if-else (continued) The general form is: if (expression) statement; or if (expression) statement; else statement;

Example – Is It Negative? Example – Write a program that determine if a number is negative or non-negative Our algorithm (recipe for a program): –Get the number –Print whether its negative or non-negative

Is It Negative? (continued) 1.Get the number 2.Print whether its negative or non-negative 1.1Ask the user for a number 1.2Read in a number

Is It Negative? (continued) 1.1Ask the user for a number 1.2Read in a number 2. Print whether its negative or non-negative 2.IF the number is negative 2.1 THEN print a message saying that it is negative 2.2 ELSE print a message saying that it is not negative

Is It Negative? (continued) 1.1Ask the user for a number 1.2Read in a number 2.IF the number is negative 2.1 THEN print a message saying that it is negative 2.2 ELSE print a message saying that it is not negative System.out.println ("Please enter a number?"); double number = keyb.nextDouble();

Is It Negative? (continued) System.out.println ("Please enter a number?"); double number = keyb.nextDouble(); 2.IF the number is negative 2.1 THEN print a message saying that it is negative 2.2 ELSE print a message saying that it is not negative if (number < 0.0) System.out.println(number + " is a negative number"); else System.out.println(number + " is a NOT negative number");

IsItNegative.java import java.util.Scanner; public class IsItNegative { // Tell a user if a number is negative or // non-negative public static void main(String[] args) { Scanner keyb = new Scanner(System.in); // Ask the user for a number System.out.println ("Please enter a number?"); double number = keyb.nextDouble();

// Print whether the number is negative or // not if (number < 0.0) System.out.println(number + " is a negative number"); else System.out.println(number + " is a NOT negative number"); }

Simple Boolean Expressions Let's take another look at the first part of an if structure: if ( condition ) A condition is either true or false; it is also called by a more formal name, a logical expression or Boolean expression, which an combination of terms that is either true or false.

Relational Operators So far, we have seen only one example of this: number < 0 We want to know if the relationship is true, i.e., is number less than 0. Since the truth or falsehood depends on this relationship, we call < a relational operator.

Relational vs. arithmetic operators Compare number < 0 to length * width. number < 0 produces a true or false length * width produces a number. In both cases, we are combining variables to produce a new result, but the type of result is entirely different.

Relational operators -x +7 <= 10 less than or equal to <= x+1 >= 0 greater than or equal to >= x-1 < 2*x less than < x+1 > y greater than > 1 != 0 is not equal to != x == y equals == ExampleMeaningOperator

Relational operators (continued) Assume that x = 4 y = 6 and z = -2 Which of the following are true? x+z >= 0 x < z x <= y x != y+z 2*x + z == y The advantage of using variables in these expressions is that the values may change from one program run to another.

Example – Calculating Speed Example - Calculate the speed that you are driving from the distance and time that you have been driving. If you are going over the speed limit, print a warning message. We know the following about our problem: Available input: Distance in miles Time in hours Required output: Speed in miles per hour Warning message (if appropriate)

Example – Calculating Speed (continued) We have to perform the following steps: 1.Read in the distance in miles and time in hours. 2.Calculate and print the speed. 3.Print the warning if appropriate.

Example – Calculating Speed (continued) 1. Read in the distance in miles and time in hours. 2. Calculate and print the speed. 3. Print the warning if appropriate. 1.1 Read distance traveled 1.2 Read the time traveled

Example – Calculating Speed (continued) 1.1 Read distance traveled 1.2 Read the time traveled 2. Calculate and print the speed. 3. Print the warning if appropriate Prompt the user for distance Read the distance Prompt the user for time Read the time

Example – Calculating Speed (continued) Prompt the user for distance Read the distance Prompt the user for time Read the time 2. Calculate and print the speed. 3. Print the warning if appropriate. 2.1 Calculate the speed 2.2 Print the speed

Example – Calculating Speed (continued) Prompt the user for distance Read the distance Prompt the user for time Read the time 2.1 Calculate the speed 2.2 Print the speed 3. Print the warning if appropriate. 3. If the speed > then print the warning

Example – Calculating Speed (continued) Prompt the user for distance Read the distance Prompt the user for time Read the time 2.1 Calculate the speed 2.2 Print the speed 3. If the speed > then print the warning System.out.println ("How many miles have you driven?"); double miles = keyb.nextDouble(); System.out.println ("How many hours did it take?"); double hours = keyb.nextDouble();

Example – Calculating Speed (continued) System.out.println ("How many miles have you driven?"); double miles = keyb.nextDouble(); System.out.println ("How many hours did it take?"); double hours = keyb.nextDouble(); 2.1 Calculate the speed 2.2 Print the speed 3. If the speed > then print the warning double speed = miles / hours; System.out.println("You were driving at " + speed + " miles per hour.");

Example – Calculating Speed (continued) System.out.println ("How many miles have you driven?"); double miles = keyb.nextDouble(); System.out.println ("How many hours did it take?"); double hours = keyb.nextDouble(); double speed = miles / hours; System.out.println("You were driving at " + speed + " miles per hour."); 3. If the speed > then print the warning if (speed > 55) System.out.println("**BE CAREFUL!**" + "You are driving too fast!");

The Complete Speed Program import java.util.Scanner; public class Speed { // Calculate the speed that you are traveling // from the distance and time that you have // been driving. // Print a warning if you are going over the // speed limit. public static void main(String[] args) { Scanner keyb = new Scanner(System.in); // Read in the distance in miles and // time driven System.out.println ("How many miles have you driven?"); double miles = keyb.nextDouble();

System.out.println ("How many hours did it take?"); double hours = keyb.nextDouble(); // Calculate and print the speed double speed = miles / hours; System.out.println("You were driving at " + speed + " miles per hour. " ); // Print the warning if appropriate if (speed > 55) System.out.println( " **BE CAREFUL!** " + " You are driving too fast! " ); }

Error Checking: The ConvertPounds Program Let’s take another look at the program which converts pounds to kilograms. Since a weight cannot be a negative number, our program should not accept a negative number as a valid weight. Let’s rewrite the program to print an error message if the weight entered in pounds is negative.

Designing ConvertPounds2 Let’s plan our algorithm: 1.Read the weight in pounds 2.If the weight in pounds is negative, print an error message; otherwise calculate and print the weight in kilograms.

Designing ConvertPounds2 Let’s plan our algorithm: 1.Read the weight in pounds 2.If the weight in pounds is negative, print an error message; otherwise calculate and print the weight in kilograms. 1.1Ask the user for the weight in pounds 1.2Read the weight in pounds

Designing ConvertPounds2 (continued) Let’s plan our algorithm: 1.1Ask the user for the weight in pounds 1.2Read the weight in pounds 2.If the weight in pounds is negative, print an error message; otherwise calculate and print the weight in kilograms. 2.IF weight in pounds is negative 2.1 THEN print an error message 2.2 ELSE calculate and print the weight in kilograms

Designing ConvertPounds2 (continued) Let’s plan our algorithm: 1.1Ask the user for the weight in pounds 1.2Read the weight in pounds 2.IF weight in pounds is negative 2.1 THEN print an error message 2.2 ELSE calculate and print the weight in kilograms if (lbs < 0)

Designing ConvertPounds2 (continued) 1.1Ask the user for the weight in pounds 1.2Read the weight in pounds if (lbs < 0) 2.1 THEN print an error message 2.2 ELSE calculate and print the weight in kilograms System.out.println(lbs + " is not a valid weight.");

Designing ConvertPounds2 (continued) 1.1Ask the user for the weight in pounds 1.2Read the weight in pounds if (lbs < 0) System.out.println(lbs + " is not a valid weight."); 2.2 ELSE calculate and print the weight in kilograms else { double kg = lbs / 2.2; System.out.println("The weight is " + kg + " kilograms");

Designing ConvertPounds2 (continued) 1.1Ask the user for the weight in pounds 1.2Read the weight in pounds if (lbs < 0) System.out.println(lbs + " is not a valid weight."); else { double kg = lbs / 2.2; System.out.println("The weight is " + kg + " kilograms"); System.out.println ("What is the weight in pounds?"); double lbs = keyb.nextDouble();

The Revised ConvertPounds import java.util.Scanner; public class ConvertPounds2 { // Convert pounds to kilograms // Input - weight in pounds // Output - weight in kilograms public static void main(String[] args) { Scanner keyb = new Scanner(System.in); // Get the weight in pounds System.out.println ("What is the weight in pounds?"); double lbs = keyb.nextDouble();

// Ensure that the weight in pounds is // valid. If it is valid, calculate and // display the weight in kilograms if (lbs < 0) System.out.println(lbs + " is not a valid weight."); else { double kg = lbs / 2.2; System.out.println("The weight is " + kg + " kilograms"); }

Constants Let's re-examine the statement in our program ConvertPounds2 that does the actual conversion: k g := lbs / 2.2; Where does come 2.2 from? (There are 2.2 pounds per kilogram) How would know why we use 2.2 if we are not familiar with the problem?

Constants (continued) We call the constant 2.2 a literal because this is literally the value that we wish to use. Any value that we write in a program, whether it is a number or a character or a character string is considered a literal. The problem with using literals is that we do not always know why this particular value appears in the program. Not knowing makes it difficult to understand precisely how the program works and makes it more difficult if we need to correct or modify the program.

Constants (continued) There is a better way to handle this. Java allows us to declare values as final (not subject to further revision); these values identified by name and their values do not and cannot change within the program. Any such constants that we declare will appear at the beginning of the procedure, where the variables are declared.

ConvertPounds3 import java.util.Scanner; public class ConvertPounds3 { // Convert pounds to kilograms // Input - weight in pounds // Output - weight in kilograms public static void main(String[] args) { Scanner keyb = new Scanner(System.in); final double lbsPerKg = 2.2; // Get the weight in pounds System.out.println ("What is the weight in pounds?"); double lbs = keyb.nextDouble();

// Ensure that the weight in pounds is // valid. If it is valid, calculate and // display the weight in kilograms if (lbs < 0) System.out.println(lbs + " is not a valid weight."); else { double kg = lbs / lbsPerKg; System.out.println("The weight is " + kg + " kilograms"); }

Declaring Constants The general form of the constant declaration is: final datatype ConstantName = ConstantValue, AnotherConstantName = AnotherConstantValue; Let's take a look at a few examples of constants: final double withholdingRate = 0.8; final char prompt = 'y'; final String answer = "yes"; final int maxPeople = 15, inchPerFt = 12; final int speedLimit = 55;

Why Use Constants? While some values (like inches/ft and lbs/kg) may never change, others will (tax rates, wages, etc.). Now the change only must be made in one place. It explains what the value represents.

Compounds Decisions We saw earlier that not all decisions are simple cases of one or two options depending on a single condition. Consider our choice of transactions at the bank: IF you want to make a deposit THEN process deposit ELSE IF you want to cash a check THEN process check ELSE IF you want to transfer money THEN process transfer ELSE IF you want to order checks THEN process order ELSE IF you want to check balance THEN process balance ELSE it must be an error

Compound Decisions (continued) Being able to do more than one statement is helpful: if (lbs < 0) System.out.println(lbs + " is not a valid weight."); else { kg = lbs / lbsperkg; System.out.println("The weight is " + kg + " kilograms"); }

Blocks Any place in a Java where a statement can appear, a block can also appear. A block is a set of statements between opening and closing braces ( { } ). Example: if (x > y){ System.out.println("x is larger"); max = x; }

An Auto Insurance Program Example - Write a program to determine the cost of an automobile insurance premium, based on driver's age and the number of accidents that the driver has had. The basic insurance charge is $500. There is a surcharge of $100 if the driver is under 25 and an additional surcharge for accidents: # of accidents Accident Surcharge or more No insurance

An Auto Insurance Program (continued) Available input –Number of accidents –driver age Required output –Insurance charge.

Designing the Insurance Program’s Algorithm Let's start with the basic algorithm: 1.Input the driver's age and number of accidents. 2.Determine the insurance charge. 3.Print the charge and all other relevant information.

Designing the Insurance Program’s Algorithm 1.Input the driver's age and number of accidents. 2.Determine the insurance charge. 3.Print the charge and all other relevant information. System.out.println("How old is the driver?"); age = keyb.nextInt(); System.out.println("How many accidents has the " + "driver had?"); numAccidents = keyb.nextInt();

Designing the Insurance Program’s Algorithm System.out.println("How old is the driver?"); age = keyb.nextInt(); System.out.println("How many accidents has the " + "driver had?"); numAccidents = keyb.nextInt(); 2.Determine the insurance charge. 3.Print the charge and all other relevant information. 2.1IF the driver is under THEN Set the Age Surcharge to $ Add on the appropriate surcharge if the driver has had accidents 2.3Add the surcharges to the rate

Designing the Insurance Program’s Algorithm System.out.println("How old is the driver?"); age = keyb.nextInt(); System.out.println("How many accidents has the " + "driver had?"); numAccidents = keyb.nextInt(); 2.1IF the driver is under THEN Set the Age Surcharge to $ Add on the appropriate surcharge if the driver has had accidents 2.3Add the surcharges to the rate 3.Print the charge and all other relevant information. if (age < 25) ageSurcharge = 100; else ageSurcharge = 0;

…… … … if (age < 25) ageSurcharge = 100; else ageSurcharge = 0; 2.2Add on the appropriate surcharge if the driver has had accidents 2.3Add the surcharges to the rate 3.Print the charge and all other relevant information. if (numAccidents == 0) accidentSurcharge = 0; else if (numAccidents == 1) accidentSurcharge = 50; else if (numAccidents == 2) accidentSurcharge = 125; else if (numAccidents == 3) accidentSurcharge = 225; else if (numAccidents == 4) accidentSurcharge = 375; else if (numAccidents == 5) accidentSurcharge = 575

…… … … if (age < 25) ageSurcharge = 100; else ageSurcharge = 0; if (numAccidents == 0) accidentSurcharge = 0; else if (numAccidents == 1) accidentSurcharge = 50; else if (numAccidents == 2) accidentSurcharge = 125; else if (numAccidents == 3) accidentSurcharge = 225; else if (numAccidents == 4) accidentSurcharge = 375; else if (numAccidents == 5) accidentSurcharge = 575; 2.3Add the surcharges to the rate 3.Print the charge and all other relevant information. rate = basicRate + ageSurcharge + accidentSurcharge; System.out.println("The total charge is $" + rate);

The Final Insurance Program import java.util.Scanner; public class CarInsurance { // A program to calculate insurance premiums // based on the driver’s age and accident // record. public static void main(String[] args) { Scanner keyb = new Scanner(System.in); final double basicRate = 500; double rate; int age, numAccidents; int ageSurcharge = 0, accidentSurcharge = 0; boolean error = false, tooMany = false;

// Input driver's age and number of // accidents System.out.println ("How old is the driver?"); age = keyb.nextInt(); System.out.println("How many accidents has " + " the driver had?"); numAccidents = keyb.nextInt(); // Determine if there is an age surcharge if (age < 0) error = true; else if (age < 25) ageSurcharge = 100; else ageSurcharge = 0;

// Determine if there is a surcharge if (numAccidents < 0) error = true; else if (numAccidents == 0) accidentSurcharge = 0; else if (numAccidents == 1) accidentSurcharge = 50; else if (numAccidents == 2) accidentSurcharge = 125; else if (numAccidents == 3) accidentSurcharge = 225; else if (numAccidents == 4) accidentSurcharge = 375; else if (numAccidents == 5) accidentSurcharge = 575; else tooMany = true;

// Print the charges if (error) System.out.println("There has been an " + " error in the data that " + " you supplied"); else if (tooMany) System.out.println("You have had too " + " many accidents for me to " + " insure you."); else { System.out.println("The basic rate is $" + basicRate); if (ageSurcharge > 0) System.out.println("There is an extra " + " surcharge of $" + ageSurcharge + " because the driver is" + " under 25.");

if (accidentSurcharge > 0) System.out.println("There is an extra " + " surcharge of $" + accidentSurcharge + " because the driver had " + numAccidents + " accident(s)."); rate = basicRate + ageSurcharge + accidentSurcharge; System.out.println("The total charge is $“ + rate); }