building java programs chapter 4 conditional execution

26
BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

Upload: buddy-hunt

Post on 18-Dec-2015

240 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

BUILDING JAVA PROGRAMSCHAPTER 4Conditional Execution

Page 2: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

days until the AP Computer Science

test

198

Page 3: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

FracCalc Demo

Page 4: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

Objectives

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

Page 5: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

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

Page 6: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

The if statementExecutes a block of statements only if a test

expression is true.

if (<test expression>) { <statement>; ...}

Syntax Yoda

Page 7: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

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

Page 8: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

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

Page 9: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

Operator Meaning Example Value

== equals 1 + 1 == 2 true

!= does not equal 3.2 != 2.5 true

< less than 10 < 5 false

> greater than 10 > 5 true

<= less than or equal to 126 <= 100 false

>= greater than or equal to 5.0 >= 5.0 true

Page 10: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

A note on ==

if (age == 17) {…}

The equality operator (==) is not to be confused with the assignment operator (=).

if (age = 17) {…}

Page 11: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

Logical OperatorsTests can be combined using logical operators:

Operator Description

Example Result

&& and (2 == 3) && (-1 < 5) false

|| or (2 == 3) || (-1 < 5) true

! not !(2 == 3) true

Page 12: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution
Page 13: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

Truth TablesTruth tables for each, used with logical values p and q:

p q p && q p || q

true true true true

true false false true

false true false true

false false false false

p !p

true false

false true

Page 14: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

Evaluating Logic ExpressionsRelational operators have lower precedence than math; logical operators have lower precedence than relational operators

5 * 7 >= 3 + 5 * (7 – 1) && 7 <= 115 * 7 >= 3 + 5 * 6 && 7 <= 1135 >= 3 + 30 && 7 <= 1135 >= 33 && 7 <= 11true && truetrue

Relational operators cannot be "chained" as in algebra2 <= x <= 10true <= 10 (assume that x is 15)Error!

Instead, combine multiple tests with && or ||2 <= x && x <= 10true && falseFalse

Page 15: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

In your notebook…int x = 42;int y = 17;int z = 25;

y < x && y <= zx <= y + z && x >= y + z(x + y) % 2 == 0 || !((z – y) % 2 == 0)

True

True

False

Page 16: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

Using boolean• Write a program where user inputs integers until the user no

longer enters a perfect square.

Enter perfect squares: 4 16 9 121 100 4 33 is not a square!

Enter perfect squares: 1 2 82 is not a perfect square!

Page 17: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

Using booleanpublic 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; } }}

Page 18: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

Homework• Read 3.1• PracticeIt 4.1, 4.2• FracCalc Checkpoint 1

Page 19: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

The if/else statementExecutes 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

Page 20: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

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!");}...

Page 21: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

Nested if/elseChooses 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

Page 22: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

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 andcomputes their body mass index (BMI).

Enter next person's information:height (in inches)? 70.0weight (in pounds)? 194.25

Enter next person's information:height (in inches)? 62.5weight (in pounds)? 130.5

Person 1 BMI = 27.868928571428572overweightPerson 2 BMI = 23.485824normalDifference = 4.3831045714285715

7032

height

weightBMI

BMI Weight classbelow 18.5 underweight18.5 - 24.9 normal25.0 - 29.9 overweight30.0 and up obese

Page 23: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

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.

Page 24: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

All paths must returnpublic 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.

Page 25: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

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 1quadrant 2

quadrant 3 quadrant 4

Page 26: BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution

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