BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution.

Slides:



Advertisements
Similar presentations
Copyright 2010 by Pearson Education Building Java Programs Chapter 4 Lecture 4-2: Advanced if/else ; Cumulative sum reading: 4.1, 4.3, 4.5; "Procedural.
Advertisements

1 BUILDING JAVA PROGRAMS CHAPTER 4 CONDITIONAL EXECUTION.
Introduction to Computer Programming Decisions If/Else Booleans.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises:
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: Scanner ; if/else reading: , 4.2, 4.6.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution.
CS305j Introduction to Computing Conditional Execution 1 Topic 12 Conditional Execution "We flew down weekly to meet with IBM, but they thought the way.
Topic 11 Scanner object, conditional execution Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Building Java Programs Chapter 4 Conditional Execution Copyright (c) Pearson All rights reserved.
Building Java Programs Chapter 4 Conditional Execution Copyright (c) Pearson All rights reserved.
Conditionals (Cont’d). 2 Nested if/else question Formula for body mass index (BMI): Write a program that produces output like the following: This program.
CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University.
Introduction to Information and Computer Science Computer Programming Lecture d This material (Comp4_Unit5d) was developed by Oregon Health and Science.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises:
Building Java Programs
Component 4: Introduction to Information and Computer Science Unit 5: Overview of Programming Languages, Including Basic Programming Concepts Lecture 4.
1 if / else statements. 2 Conditionals “If you eat your vegetables, then you can have dessert.” “If you do your homework, then you may go outside to play,
Building Java Programs Chapter 4 Conditional Execution Copyright (c) Pearson All rights reserved.
1 CSE 142 Lecture Notes Conditional Execution with if Statements; Methods that Return Values (briefly) Chapters 3 and 4 Suggested reading: ;
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises:
Copyright 2010 by Pearson Education Building Java Programs Scanner ; if / else; while loops ; random reading: 3.3 – 3.4, 4.1, 4.5, 5.1, 5.6.
Copyright 2008 by Pearson Education 1 The if statement Executes a block of statements only if a test is true if ( test ) { statement ;... statement ; }
Copyright 2010 by Pearson Education The if/else statement reading: 4.1, 4.6.
CSc 110, Autumn 2016 Lecture 9: input ; if/else Adapted from slides by Marty Stepp and Stuart Reges.
Building Java Programs
Building Java Programs Chapter 4
Building Java Programs
Conditional Execution
Building Java Programs Chapter 4
Lecture 4: Program Control Flow
Factoring if/else code
Building Java Programs
Adapted from slides by Marty Stepp and Stuart Reges
Lecture 4: Conditionals
Topic 11 Scanner object, conditional execution
Building Java Programs
CSc 110, Spring 2017 Lecture 8: input; if/else
Building Java Programs
Adapted from slides by Marty Stepp and Stuart Reges
Building Java Programs Chapter 4
Building Java Programs
Executes a block of statements only if a test is true
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Lecture 6: Conditionals AP Computer Science Principles
Factoring if/else code
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Chapter 2 Programming Basics.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Chapter 4 Lecture 4-1: Scanner; if/else reading: 3.3 – 3.4, 4.1, 4.5
Building Java Programs Chapter 4
Building Java Programs
Factoring if/else code
Building Java Programs
Presentation transcript:

BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

days until the AP Computer Science test

FracCalc Demo

Objectives Describe how an if statement works. List the relational operators. Define logical AND, OR, and NOT operators. Compute boolean expressions.

public static void withdraw(int balance, int amount) { balance -= amount; System.out.println(“New balance: “ + balance); return balance; } What’s wrong? int balance = 100; balance = withdraw(balance, 10); balance = withdraw(balance, 20); balance = withdraw(balance, 300);

The if statement Executes a block of statements only if a test expression is true. if ( ) { ;... } Syntax Yoda

public static void withdraw(int balance, int amount) { if(balance >= amount) { balance -= amount; System.out.println(“New balance:” + balance); } return balance; } int balance = 100; balance = withdraw(balance, 10); balance = withdraw(balance, 20); balance = withdraw(balance, 300);

Relational Expressions if statements and for loops both use logical tests. for (int i = 1; i <= 10; i++) {... } if (i <= 10) {... } These are boolean expressions and will be covered in Chapter 5. Tests use relation operators.

OperatorMeaningExampleValue == equals == 2true != does not equal 3.2 != 2.5true < less than 10 < 5false > greater than 10 > 5true <= less than or equal to 126 <= 100false >= greater than or equal to 5.0 >= 5.0true

A note on == if (age == 17) {…} The equality operator (==) is not to be confused with the assignment operator (=). if (age = 17) {…}

Logical Operators Tests can be combined using logical operators: OperatorDescriptionExampleResult && and (2 == 3) && (-1 < 5)false || or (2 == 3) || (-1 < 5)true ! not !(2 == 3)true

Truth Tables Truth tables for each, used with logical values p and q: pqp && qp || q true false true falsetruefalsetrue false p!p truefalse true

Evaluating Logic Expressions Relational operators have lower precedence than math; logical operators have lower precedence than relational operators 5 * 7 >= * (7 – 1) && 7 <= 11 5 * 7 >= * 6 && 7 <= >= && 7 <= >= 33 && 7 <= 11 true && true true Relational operators cannot be "chained" as in algebra 2 <= x <= 10 true <= 10 (assume that x is 15) Error! Instead, combine multiple tests with && or || 2 <= x && x <= 10 true && false False

In your notebook… int x = 42; int y = 17; int z = 25; y < x && y <= z x = y + z (x + y) % 2 == 0 || !((z – y) % 2 == 0) True False

Using boolean Write a program where user inputs integers until the user no longer enters a perfect square. Enter perfect squares: is not a square! Enter perfect squares: is not a perfect square!

Using boolean public static void main(String args[]) { Scanner console = new Scanner(System.in); System.out.println(“Enter perfect squares: ”); for(boolean shouldExit = false; shouldExit;) { int input = console.nextInt(); int sqrt = (int)(Math.sqrt(input)); if (sqrt * sqrt != input) { System.out.println(input + “ is not a perfect square!”); shouldExit = true; }

Homework Read 3.1 PracticeIt 4.1, 4.2 FracCalc Checkpoint 1

The if/else statement Executes one block if a test is true, another if false if (test) { statement(s); } else { statement(s); } Example: double gpa = console.nextDouble(); if (gpa >= 2.0) { System.out.println("Welcome to Mars University!"); } else { System.out.println("Application denied."); } Syntax Yoda

Misuse of if What's wrong with the following code? Scanner console = new Scanner(System.in); System.out.print("What percentage did you earn? "); int percent = console.nextInt(); if (percent >= 90) { System.out.println("You got an A!"); } if (percent >= 80) { System.out.println("You got a B!"); } if (percent >= 70) { System.out.println("You got a C!"); } if (percent >= 60) { System.out.println("You got a D!"); } if (percent < 60) { System.out.println("You got an F!"); }...

Nested if/else Chooses between outcomes using many tests if (test) { statement(s); } else if (test) { statement(s); } else { statement(s); } Example: if (x > 0) { System.out.println("Positive"); } else if (x < 0) { System.out.println("Negative"); } else { System.out.println("Zero"); } Syntax Yoda

Let’s Try It! Formula for body mass index (BMI): Write a program that produces output like the following: This program reads data for two people and computes their body mass index (BMI). Enter next person's information: height (in inches)? 70.0 weight (in pounds)? Enter next person's information: height (in inches)? 62.5 weight (in pounds)? Person 1 BMI = overweight Person 2 BMI = normal Difference = BMIWeight class below 18.5underweight normal overweight 30.0 and upobese

if/else with return // Returns the larger of the two given integers. public static int max(int a, int b) { if (a > b) { return a; } else { return b; } Methods can return different values using if/else Whichever path the code enters, it will return that value. Returning a value causes a method to immediately exit. All paths through the code must reach a return statement.

All paths must return public static int max(int a, int b) { if (a > b) { return a; } // Error: not all paths return a value } The following also does not compile: public static int max(int a, int b) { if (a > b) { return a; } else if (b >= a) { return b; } } The compiler thinks if/else if code might skip all paths, even though mathematically it must choose one or the other.

if/else, return question Write a method quadrant that accepts a pair of real numbers x and y and returns the quadrant for that point: Example: quadrant(-4.2, 17.3) returns 2 If the point falls directly on either axis, return 0. x+ x- y+ y- quadrant 1 quadrant 2 quadrant 3 quadrant 4

Homework Read 3.1 Self Check 4.1, 4.2, 4.4, 4.13, Exercise 4.3, 4.4 FracCalc Checkpoint 1