Chapter 3. Ch 1 Introduction to Computers and Java. Selections

Similar documents
Chapter 5 Lab Methods

Midterm Examination (MTA)

Loops. CSE 114, Computer Science 1 Stony Brook University

Chapter 1 Lab Algorithms, Errors, and Testing

Lesson 7 Part 2 Flags

Oct Decision Structures cont d

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Introduction to Computer Science Unit 2. Notes

Basic Computation. Chapter 2

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Chapter 5 Lab Methods

Bjarne Stroustrup. creator of C++

Over and Over Again GEEN163

H212 Introduction to Software Systems Honors

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Loops. GEEN163 Introduction to Computer Programming

Selections. CSE 114, Computer Science 1 Stony Brook University

Full file at

Chapter 4: Conditionals and Recursion

1 Short Answer (10 Points Each)

Flow of Control: Loops. Chapter 4

Conditional Programming

Control Structures: if and while A C S L E C T U R E 4

Logic & program control part 3: Compound selection structures

Introduction to Computer Science Unit 2. Notes

Enumerated Types. CSE 114, Computer Science 1 Stony Brook University

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

COMP 202 Java in one week

Full file at

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

CS1150 Principles of Computer Science Boolean, Selection Statements

1 Definitions & Short Answer (4 Points Each)

Basic Computation. Chapter 2

STUDENT LESSON A12 Iterations

Darrell Bethea May 25, 2011

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

CS141 Programming Assignment #5

Chapter 4: Control Structures I

CEN 414 Java Programming

Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly

Following is the general form of a typical decision making structure found in most of the programming languages:

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Flow of Control. Chapter 3

In this chapter, you will:

CS 455 Midterm Exam 1 Fall 2015 [Bono] Thursday, Oct. 1, 2015

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 3: Operators, Expressions and Type Conversion

Program Control Flow

Program Control Flow

Chapter 3. Selections

Java Coding 2. Decisions, decisions!

Topic 5: Enumerated Types and Switch Statements

Chapter 3 Lab Decision Structures

1 Short Answer (5 Points Each)

COMP 202. Java in one week

New York University Introduction to Computer Science Midterm2 Sample Problems 2013 Andrew I. Case. Instructions:

Decisions: Logic Java Programming 2 Lesson 7

CSCE 314 Programming Languages

Full file at

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Question: Total Points: Score:

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Ch. 6. User-Defined Methods

Lecture 8 " INPUT " Instructor: Craig Duckett

Repetition. Chapter 6

Logic & program control part 2: Simple selection structures

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

Repetition. Chapter 6

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Flow of Control. Chapter 3 Part 3 The Switch Statement

if Statement Numeric Rela5onal Operators The if Statement Flow of Control: Branching (Savitch, Chapter 3)

Fundamentals of Programming Data Types & Methods

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

if Statement Numeric Rela7onal Operators The if Statement Flow of Control: Branching (Savitch, Chapter 3)

Task #1 The if Statement, Comparing Strings, and Flags

Flow of Control. Chapter 3

Conditional Execution

CS 170 Section 3, Spring 2015 Programming in Java Midterm Exam 1. Name (print):

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

King Saud University College of Computer and Information Sciences Computer Science Department

Chapter 5 Lab Methods

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Warm-Up: COMP Programming with Iterations 1

Honors Computer Programming 1-2. Chapter 5 Exam Prep

CS 112 Introduction to Programming

CS 112 Introduction to Programming

CSIS 10A Assignment 4 SOLUTIONS

A+ Computer Science -

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

ITERATION WEEK 4: EXMAPLES IN CLASS

CS 170 Section 3, Spring 2015 Programming in Java Midterm Exam 1. Name (print):

4. Java Project Design, Input Methods

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

Outline. Java Compiler and Virtual Machine. Why Java? Naming Conventions. Classes. COMP9024: Data Structures and Algorithms

COE 212 Engineering Programming. Welcome to Exam I Tuesday November 11, 2014

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

Transcription:

Chapter 3 Ch 1 Introduction to Computers and Java Selections 1

The if-else Statement 2

Flow Chart Deconstructed Decision: Make a choice Start Terminator: Show start/stop points T boolean expression F true statements false statement Process: Statements to execute Connector: Connect lines Stop 3 A flow chart is an easy way to graphically express your logic, without having to write any code. You are encouraged to develop your flowcharting skills as a means to express your solution graphically. As a programmer you are constantly asked to solve problems, and using algorithms is how you present your step by step solution to the problem at hand, that does not require the use of code. So, an algorithm, being your recipe of steps to follow in order to solve a particular problem can be graphically represented with a flowchart. It is another way to show the same results, one text base and the other graphical based.

Flow Chart Deconstructed <Taxes owed> Start income <= NO_TAX_AMOUNT income > NO_TAX_AMOUNT taxesowed = 0.0 taxesowed = income * TAX_RATE Stop 4 In the example demonstrated above, we begin with the "Start" terminator as the beginning of our algorithm. We then have to make a choice, is the income less than or equal to the no tax amount? This choice is shown with the use of the "Decision" symbol, and as shown, it has two possible outcomes, True or False. If the income is less than or equal to the no tax amount, we execute the statement(s) on the left, i.e. we assign 0.0 to the variable taxesowed. If the income is greater, we execute the statement(s) on the right, which assigns the quantity income * TAX_RATE to the income variable. As you can see from above, one of two outcomes is possible. We say that the choices are mutually exclusive, only one of the two will ever execute after a decision has been made. Once a decision has been made and one of the two outcomes is executed, then execution continues with the steps that follow. This is indicated with the conversion of the flow lines into the "Connector" and ultimately the "Stop" terminator.

If else Deconstructed <Taxes owed>... boolean expression if (income <= NO_TAX_AMOUNT) { taxesowed = 0.0; true statements } else { taxesowed = income * TAX_RATE; false statements } //end if... 5 Java provides the if control structure for making decisions. The above example shows a decision with two possible outcomes, thus an if-else is used. The statements after the if boolean expression make up the true block, and the statements after the else make up the false block. Keep in mind that the else part is always optional and its use depends on how many possible outcomes you have. If you have one, then it is not used, if two it is used.

Application Deconstructed <TaxesOwed.java> package taxesowed; import java.util.scanner; public class TaxesOwed { public static final double NO_TAX_AMOUNT = 10000.0; public static final double TAX_RATE = 0.03; public static void main(string[] args) { double income; double taxesowed; Scanner keyboard = new Scanner(System.in); System.out.print("Enter your income amount: $"); income = keyboard.nextdouble(); 6

Application Deconstructed <TaxesOwed.java> if (income <= NO_TAX_AMOUNT) { taxesowed = 0.0; } else { taxesowed = income * TAX_RATE; }// end else System.out.println("You owe $" + taxesowed + " on an income of $" + income); }// end main() }// end TaxesOwed 7

Boolean expressions may use the following relational operators Operation Operator Example equality == a == b inequality!= a!= b greater than > a > b greater than or equal >= a >= b less than < a < b less than or equal <= a <= b 8 The relational operators or comparison operators allow you to perform a number of comparisons whose outcome is a boolean result, i.e. either true or false. Warning: The equality is expressed with two equal signs, not one, so be careful as the latter will cause an error. For example, if (a = b) is not the same as if (a == b), and will make the compiler very unhappy. The equality works as expected with integral values, but not so well with floating point and strings. Floating point variables recall, may be simply approximations of the actual numbers, thus comparison may lead to undesirable results. It is best to compare the difference of the two against an acceptable margin of error. Strings also pose a problem, since strings are actually objects. An object variable is nothing more than a reference (pointer) to the actual value of the object in memory, and thus two separate memory locations could have the exact same string value, but since their memory locations are different, the relational operators will result in an inaccurate outcome. An example of this is shown next.

... and the following logical operators Operation Operator Example And && (a < b) && (c > d) Or (a == b) (c == d) Not!!fileIsOpen 9 Logical operators can be used to create compound expressions. The meaning of the operators is similar to what you may have learned while studying boolean algebra. Here is the low down on each one. && : True only when both arguments are true, false otherwise. : False only when both argumenst are false, true otherwise.! : The complement of its argument. This one should be avoided in expressions using the relational operators, since it leads to unreadable code. For example,!(c < 0) is best expressed as (c >= 0), a more readable form.

Application Deconstructed <StringEquality.java> package stringequality; import java.util.scanner; public class StringEquality { public static void main(string[] args) { String str1; String str2; Scanner keyboard = new Scanner(System.in); System.out.print("Enter some text: "); str1 = keyboard.nextline(); System.out.print("Enter more text: "); str2 = keyboard.nextline(); 10

Application Deconstructed <StringEquality.java> System.out.println(); System.out.println("str1 = \"" + str1 + "\" : str2 = \"" + str2 + "\""); System.out.println(); System.out.println("str1 == str2? " + (str1 == str2)); System.out.println("str1.equals(str2)? " + str1.equals(str2)); System.out.println("str2.equals(str1)? " + str2.equals(str1)); 11 Notice how the test str1 == str2 evaluates to false, even though the two string objects have the same value. This is important to understand because it underlies the fact that object variables (str1, str2 in this example) are merely references (pointers) to the actual objects, which both happen to the have the same value ("Apples are red"), but are in different memory locations. For proper string value comparisons, use the method.equals().

Application Deconstructed <StringEquality.java> str2 = "apples are red"; System.out.println(); System.out.println("str1 = \"" + str1 + "\" : str2 = \"" + str2 + "\""); System.out.println(); System.out.println("str1.equals(str2)? " + str1.equals(str2)); System.out.println("str1.equalsIgnoreCase(str2)? " + str1.equalsignorecase(str2)); }// end main() }// end StringEquality 12 Since Java is case sensitive, if you want to compare two strings without accounting for the case, then use the method.equalsignorecase(), as shown above. This method treats uppercase the same as lowercase.

Application Deconstructed <StringEquality.java> 13

Application Deconstructed <MultiBranchIf.java> package multibranchif; import java.util.scanner; public class MultiBranchIf { public static final int SUN = 1; public static final int MON = 2; public static final int TUE = 3; public static final int WED = 4; public static final int THU = 5; public static final int FRI = 6; public static final int SAT = 7; constants for the days of the week public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); int weekdaynumber; String weekdayname = ""; 14 Notice the use of constants to aid readability and maintenance. If a change is needed later on to one of these values, then all you have to do is change one constant value. You will not have to search all of your code for each occurrence of the value itself.

Application Deconstructed <MultiBranchIf.java> System.out.print("Enter the day of the week [1-Sunday...7-Saturday]: "); weekdaynumber = keyboard.nextint(); if (weekdaynumber == SUN) { weekdayname = "Sunday"; }else if (weekdaynumber == MON) { This is just an weekdayname = "Monday"; if else, where }else if (weekdaynumber == TUE) { weekdayname = "Tuesday"; each else }else if (weekdaynumber == WED) { contains an if weekdayname = "Wednesday"; else. }else if (weekdaynumber == THU) { weekdayname = "Thursday"; }else if (weekdaynumber == FRI) { weekdayname = "Friday"; }else if (weekdaynumber == SAT) { weekdayname = "Saturday"; }// end if 15 Recall that this if-else if structure is an if-else with nested if's inside the else. For instance, if (...) {... }else if (...) {... } else { } can be rewritten as: if (...) {... } else { if (...) { } else { } }

Application Deconstructed <MultiBranchIf.java> System.out.println("I see you chose " + weekdayname + "."); }// end main() }// end MultiBranchIf 16

The conditional operator is very handy // The following if-else: if (minute == 60) { minute = 0; } else { minute += 1; } // can be written with a conditional operator as: minute = (minute == 60)? 0 : minute + 1; 17 The conditional operator is just like an if-else. An expression is given in parentheses followed by a question mark; this constitues your boolean expression in an if. If the expression evaluates to true then the first part between the? and the : is executed. This is the equivalent of the true block in an if. Next comes the part between the : and the ;. This is the equivalent of the false block in an if.

Recap Use flowcharts to express algorithms. Use the if for decisions. Use.equals or.equalsignorecase with strings 18

The Type boolean True or False? 19

Boolean expressions evaluate to true or false number > 0 True if number > 0, false otherwise 3 > 4 False 3 True, since not 0 20 Every boolean expression must evaluate to either true or false. Zero means false, and any non zero value means true.

Boolean variables simplify // Testing for leap year. if ( (year % 100!= 0) && (year % 4 == 0) (year % 400 == 0) ) { // leap year } The && has higher priority than // Testing for leap year. boolean isleap = (year % 100!= 0) && (year % 4 == 0) (year % 400 == 0); if (isleap) { // leap year } The second "if" is a lot easier to read and thus should be preferred over the first example, which is a lot hard to read and debug. A boolean variable can receive the evaluation of a boolean expression, as in: boolean isofage = (age > 21); The variable isofage will be true if age > 21, false otherwise.

Be mindful of the order of evaluation Parentheses go first, then Arithmetic, then Relational, and then Logical

Brainteaser time! int x = 3 * 5 + (4 5) / 2 + 6 % 4; bool goahead = 5 > 3 3 + 5 < 3 * 2; bool israining = true; bool haveumbrella = false; bool gotwet = israining &&!haveumbrella;

Booleans use true or false boolean isold = true; System.out.println("isOld = " + isold); // displays isold = true System.out.print("Answer true or false. This is fun: "; boolean isofage = keyboard.nextboolean(); // IO Answer true of false. This is fun: true 24

Recap Booleans hold either true or false. (), arithmetic, relational, logical, in that order. Boolean variables simplify code. 25

case 1 True statements The switch statement False case n False True statements default 26

Switch Deconstructed switch (expression) { case label1: statements; [break]; break is optional sdk 7: label can be a string default is optional case label2: statements; [break];... default: } statements; [break];

Switch Deconstructed <DayOfTheWeek> //... code omitted switch (dayoftheweek) { case MON: case TUE: case WED: case THU: case FRI: System.out.println("Bah, still a work day!"); break; case SAT: case SUN: default: } System.out.println("Woo hoo, weekend!); break; System.out.println("No comprendo!"); break; 28 Evaluation will begin at the top of the switch, and as soon as one case is selected, its body will execute and the switch will exit. If none of the cases are selected, then the default case will execute. If the break is omitted from any case then after its body is executed, control will always continue with the next case that follows.

Brainteaser time! Draw the flow chart for the DayOfTheWeek switch

Application Deconstructed <DayOfTheWeek.java> package dayoftheweek; import java.util.scanner; public class DayOfTheWeek { public static final int SUN = 1; public static final int MON = 2; public static final int TUE = 3; public static final int WED = 4; public static final int THU = 5; public static final int FRI = 6; public static final int SAT = 7; public static void main(string[] args) { int dayoftheweek; Scanner keyboard = new Scanner(System.in); 30

Application Deconstructed <DayOfTheWeek.java> System.out.print("Enter the day of the week [Sun = 1...Sat = 7]: "); dayoftheweek = keyboard.nextint(); day!"); switch (dayoftheweek) { case MON: case TUE: case WED: case THU: case FRI: System.out.println("Bah, still a work break; case SAT: case SUN: System.out.println("Woo hoo, weekend!"); break; default: System.out.println("No comprendo!"); break; }// end switch }// end main() }// end DayOfTheWeek 31