building java programs chapter 4 conditional execution
TRANSCRIPT
BUILDING JAVA PROGRAMSCHAPTER 4Conditional Execution
days until the AP Computer Science
test
198
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 statementExecutes a block of statements only if a test
expression is true.
if (<test expression>) { <statement>; ...}
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 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.
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
A note on ==
if (age == 17) {…}
The equality operator (==) is not to be confused with the assignment operator (=).
if (age = 17) {…}
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
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
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
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
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!
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; } }}
Homework• Read 3.1• PracticeIt 4.1, 4.2• FracCalc Checkpoint 1
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
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/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
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
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 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.
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
Homework• Read 3.1• Self Check 4.1, 4.2, 4.4, 4.13, • Exercise 4.3, 4.4• FracCalc Checkpoint 1