Building Java Programs

Slides:



Advertisements
Similar presentations
BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution.
Advertisements

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.
1 BUILDING JAVA PROGRAMS CHAPTER 4 CONDITIONAL EXECUTION.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution.
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.
Running JavaScript Chapter 18.
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.
Building Java Programs Chapter 4 Conditional Execution Copyright (c) Pearson All rights reserved.
Topic 12 more if/else, cumulative algorithms, printf Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
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:
Decision Making - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 10/27/20151.
Building Java Programs
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 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.
1 Building Java Programs Chapter 4: Conditional Execution These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted,
Building Java Programs
Building Java Programs Chapter 4
Building Java Programs
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
Building Java Programs Chapter 4
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Executes a block of statements only if a test is true
CSc 110, Autumn 2016 Lecture 9: input; if/else
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Lecture 6: Conditionals AP Computer Science Principles
Building Java Programs
Building Java Programs
Building Java Programs
Scanner objects Readings: 3.4.
Building Java Programs
Building Java Programs
Boolean logic suggested reading: 5.2.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Scanner objects Readings: 3.4.
Building Java Programs
Indefinite loop variations
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
Building Java Programs
Presentation transcript:

Building Java Programs Chapter 4: Conditional Execution These lecture notes are copyright (C) Marty Stepp and Stuart Reges, 2006. They may not be rehosted, sold, or modified without expressed permission from the authors. All rights reserved.

Chapter outline conditional execution the if statement the if/else statement relational expressions nested if/else statements subtleties of conditional execution factoring if/else code comparing objects with the .equals method methods with conditional execution revisiting return values

if/else statements suggested reading: 4.2

The if statement if statement: A Java statement that executes a block of statements only if a certain condition is true. If the condition is not true, the block of statements is skipped. General syntax: if (<condition>) { <statement(s)> ; } Example: double gpa = console.nextDouble(); if (gpa >= 2.0) { System.out.println("Your application is accepted.");

if statement flow diagram

The if/else statement if/else statement: A Java statement that executes one block of statements if a certain condition is true, and a second block of statements if the condition is not true. General syntax: if (<condition>) { <statement(s)> ; } else { } Example: double gpa = console.nextDouble(); if (gpa <= 2.0) { System.out.println("Your application is denied."); System.out.println("Welcome to Mars University!");

if/else flow diagram

Relational expressions The <condition> used in an if or if/else statement is the same kind of value seen in the middle of a for loop. for (int i = 1; i <= 10; i++) { The conditions are actually of type boolean, seen in Ch. 5. These conditions are called relational expressions and use one of the following six relational operators: Operator Meaning Example Value == equals 1 + 1 == 2 true != does not equal 3.2 != 2.5 < less than 10 < 5 false > greater than 10 > 5 <= less than or equal to 126 <= 100 >= greater than or equal to 5.0 >= 5.0 Note that == tests equality, not = . The = is used for the assignment operator!

Evaluating rel. expressions Relational operators have a lower precedence than mathematical operators. Example: 5 * 7 >= 3 + 5 * (7 - 1) 5 * 7 >= 3 + 5 * 6 35 >= 3 + 30 35 >= 33 true Relational operators cannot be "chained" as they can in algebra. 2 <= x <= 10 true <= 10 error!

if/else question Write code to read a number from the user and print whether that number is even or odd using an if/else statement. Example executions: Type a number: 42 Your number is even Type a number: 17 Your number is odd

Loops with if/else Loops can be used with if/else statements: int nonnegatives = 0, negatives = 0; for (int i = 1; i <= 10; i++) { int next = console.nextInt(); if (next >= 0) { nonnegatives++; } else { negatives++; } A loop that prints the factors of a number: public static void printFactors(int n) { for (int i = 1; i <= n; i++) { if (n % i == 0) { System.out.println(i + " is a factor");

Nested if/else statements Nested if/else statement: A chain of if/else that can select between many different outcomes based on several conditions. General syntax (shown here with three different outcomes): if (<condition>) { <statement(s)> ; } else if (<condition>) { } else { } A nested if/else statement can end with an if or an else. Example: if (place == 1) { System.out.println("You win the gold medal!"); } else if (place == 2) { System.out.println("You win a silver medal!"); } else if (place == 3) { System.out.println("You earned a bronze medal."); How could we modify it to print a message to non-medalists?

Nested if/else flow diagram if (<condition>) { <statement(s)> ; } else if (<condition>) { } else { }

Nested if/else/if flow diagram if (<condition>) { <statement(s)> ; } else if (<condition>) { }

Sequential if flow diagram if (<condition>) { <statement(s)> ; }

Structures of if/else code Choose 1 of many paths: (use this when the conditions are mutually exclusive) if (<condition>) { <statement(s)>; } else if (<condition>) { } else { } Choose 0 or 1 of many paths: (use this when the conditions are mutually exclusive and any action is optional) Choose 0, 1, or many of many paths: (use this when the conditions/actions are independent of each other)

Which nested if/else to use? Which if/else construct is most appropriate to perform each of the following tasks? Reading the user's GPA and printing whether the student is on the dean's list (3.8 to 4.0) or honor roll (3.5 to 3.8). Printing whether a number is even or odd. Printing whether a user is lower-class, middle-class, or upper-class based on their income. Reading a number from the user and printing whether it is divisible by 2, 3, and/or 5. Printing a user's grade of A, B, C, D, or F based on their percentage in the course.

How to comment: if/else Comments on an if statement don't need to describe exactly what the if statement is testing. Instead, they should describe why you are performing that test, and/or what you intend to do based on its result. Bad example: // Test whether student 1's GPA is better than student 2's if (gpa1 > gpa2) { // print that student 1 had the greater GPA System.out.println("The first student had the greater GPA."); } else if (gpa2 > gpa1) { // print that student 2 had the greater GPA System.out.println("The second student's GPA was higher."); } else { // there was a tie System.out.println("There has been a tie!"); } Better example: // Print a message about which student had the higher grade point average. } else { // gpa1 == gpa2 (a tie)

How to comment: if/else 2 If an if statement's test is straightforward, and if the actions to be taken in the bodies of the if/else statement are very different, sometimes putting comments on the bodies themselves is more helpful. Example: if (guessAgain == 1) { // user wants to guess again; reset game state and // play another game System.out.println("Playing another game."); score = 0; resetGame(); play(); } else { // user is finished playing; print their best score System.out.println("Thank you for playing."); System.out.println("Your score was " + score); }

Math.max/min vs. if/else Many if/else statements that choose the larger or smaller of 2 numbers can be replaced by a call to Math.max or Math.min. int z; // z should be larger of x, y if (x > y) { z = x; } else { z = y; } int z = Math.max(x, y); double d = a; // d should be smallest of a, b, c if (b < d) { d = b; } if (c < d) { d = c; } double d = Math.min(a, Math.min(b, c));

Subtleties of conditional execution suggested reading: 4.3

Factoring if/else code factoring: extracting a common part of code to reduce redundancy Factoring if/else code reduces the size of the if and else statements and can sometimes eliminate the need for if/else altogether. Example: int x; if (a == 1) { x = 3; } else if (a == 2) { x = 5; } else { // a == 3 x = 7; } int x = 2 * a + 1;

Code in need of factoring The following example has a lot of redundant code in the if/else: if (money < 500) { System.out.println("You have, $" + money + " left."); System.out.print("Caution! Bet carefully."); System.out.print("How much do you want to bet? "); bet = console.nextInt(); } else if (money < 1000) { System.out.print("Consider betting moderately."); } else { System.out.print("You may bet liberally."); }

Code after factoring If the beginning of each if/else branch is essentially the same, try to move it out before the if/else. If the end of each if/else branch is the same, try to move it out after the if/else. System.out.println("You have, $" + money + " left."); if (money < 500) { System.out.print("Caution! Bet carefully."); } else if (money < 1000) { System.out.print("Consider betting moderately."); } else { System.out.print("You may bet liberally."); } System.out.print("How much do you want to bet? "); bet = console.nextInt();

Comparing objects: .equals The relational operators such as < and == only behave correctly on primitive values. Objects such as String, Point, and Color should be compared for equality by calling a method named equals. Example (incorrect): String name = console.next(); if (name == "Teacher") { System.out.println("You must be a swell person!"); } This example code will compile, but it will never print the message. The == operator on Strings usually returns false even when the Strings have the same letters in them. Example (correct): if (name.equals("Teacher")) {

String condition methods There are several methods of a String object that can be used as conditions in if statements: Method Description equals(String) whether two Strings contain exactly the same characters equalsIgnoreCase(String) whether two Strings contain the same characters, ignoring upper vs. lower case differences startsWith(String) whether one String contains the other's characters at its start endsWith(String) whether one String contains the other's characters at its end

String condition examples Scanner console = new Scanner(System.in); System.out.print("Type your full name and title: "); String name = console.nextLine(); if (name.endsWith("Ph. D.")) { System.out.println("Hello, doctor!"); } if (name.startsWith("Ms.")) { System.out.println("Greetings, Ma'am."); if (name.equalsIgnoreCase("boss")) { System.out.println("Welcome, master! Command me!"); if (name.toLowerCase().indexOf("jr.") >= 0) { System.out.println("Your parent has the same name!");