Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops.

Slides:



Advertisements
Similar presentations
Flow of Control Usually the order of statement execution through a method is linear: one after another flow of control: the order statements are executed.
Advertisements

1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Flow of Control (1) : Logic Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Comparing Data Comparing More than Numbers. Comparing Data When comparing data using boolean expressions, it's important to understand the nuances of.
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
ECE122 L8: More Conditional Statements February 7, 2007 ECE 122 Engineering Problem Solving with Java Lecture 8 More Conditional Statements.
Java Program Statements Selim Aksoy Bilkent University Department of Computer Engineering
Logical Operators and Conditional statements
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 Conditionals and Loops Now we will examine programming statements.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Midterm Review Chapter 1  Know program style guidelines Evaluate expressions  Order of operations.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 3: Program Statements
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
© 2006 Pearson Education 1 Obj: to use compound Boolean statements HW: p.184 True/False #1 – 6 (skip 3)  Do Now: 1.Test your “Charge Account Statement”
CSCI 1100/1202 January 28, The switch Statement The switch statement provides another means to decide which statement to execute next The switch.
Chapter 3: Program Statements
Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing.
1 Data Comparisons and Switch Data Comparisons Switch Reading for this class: L&L 5.3,
© 2004 Pearson Addison-Wesley. All rights reserved February 17, 2006 The ‘while’ Statement ComS 207: Programming I (in Java) Iowa State University, SPRING.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
1 Chapter 3 Selections. 2 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator.
CSC 1051 M.A. Papalaskari, Villanova University Conditional Statements Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University.
5-1 Chapter 5: Conditionals and Loops Topics: –Boolean expressions –Conditional statements –Increment and Decrement Operators (Chapter 2.4) –Repetition.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/29 The switch Statement The switch statement provides another way.
Topics Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement The for loop Nested Loops.
Chapter 5 Conditionals and Loops 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights.
Control Flow. Data Conversion Promotion happens automatically when operators in expressions convert their operands For example, if sum is a float and.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
Control statements Mostafa Abdallah
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Design A software design specifies how a program will accomplish its requirements A design includes one or more algorithms to accomplish its goal.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Conditionals and Loops Now we will examine programming statements that allow us to: – make decisions – repeat processing steps in a loop Chapter 5 focuses.
Chapter 5 Conditionals and Loops
Operator Precedence Operators Precedence Parentheses () unary
Boolean Expressions and If
Boolean Expressions & the ‘if’ Statement
Flow of Control Unless specified otherwise, the order of statement execution through a method is linear: one after another Some programming statements.
Logical Operators & Truth Tables.
Chapter 3: Program Statements
Outline Boolean Expressions The if Statement Comparing Data
The ‘while’ Statement September 27, 2006
CS139 October 11, 2004.
Logic of an if statement
CSC 1051 – Data Structures and Algorithms I
Outline Software Development Activities
CprE 185: Intro to Problem Solving (using C)
Conditionals and Loops
Boolean Expressions & the ‘if’ Statement
CprE 185: Intro to Problem Solving (using C)
3.0 - Design A software design specifies how a program will accomplish its requirements A design includes one or more algorithms to accomplish its goal.
Presentation transcript:

Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Flow of Control Usually the order of statement execution through a method is linear: one after another flow of control: the order statements are executed Some programming statements allow us to make decisions and perform repetitions These decisions are based on boolean expressions (also called conditions) that evaluate to true or false Copyright © 2012 Pearson Education, Inc.

Conditional Statements A conditional statement lets us choose which statement will be executed next They are sometimes called selection statements Conditional statements give us the power to make basic decisions The Java conditional statements are the: –if and if-else statement –switch statement We'll explore the switch statement in Chapter 6 Copyright © 2012 Pearson Education, Inc.

The if condition Statement if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. If the condition is true, the statement is executed. If it is false, the statement is skipped. Copyright © 2012 Pearson Education, Inc. A conditional statement lets us choose which statement will be executed next

Logic of an if statement condition evaluated statement true false Copyright © 2012 Pearson Education, Inc. Can use if to code things like: if total > 100 print “$” + total / 100

The if-else Statement if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both Copyright © 2012 Pearson Education, Inc.

Logic of an if-else statement condition evaluated statement1 true false statement2 Copyright © 2012 Pearson Education, Inc. Can use if to code things like: if total > 100 print “$” + total / 100 else print total + “ cents”

Logic of an if-else statement total > 100? print “$” + total / 100 truefalse print total + “ cents” Copyright © 2012 Pearson Education, Inc. Can use if to code things like: if total > 100 print “$” + total / 100 else print total + “ cents” Boolean expression

Boolean Expressions A condition often uses one of Java's equality operators or relational operators, which all return boolean results: == equal to != not equal to < less than > greater than <= less than or equal to >= greater than or equal to Note the difference between the equality operator ( == ) and the assignment operator ( = ) Copyright © 2012 Pearson Education, Inc.

Boolean Expressions An if statement with its boolean condition: if (sum > MAX) delta = sum – MAX; First, the condition is evaluated: the value of sum is either greater than the value of MAX, or it is not If the condition is true, the assignment statement is executed; if it isn't, it is skipped See Age.java Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // Age.java Author: Lewis/Loftus // // Demonstrates the use of an if statement. //******************************************************************** import java.util.Scanner; public class Age { // // Reads the user's age and prints comments accordingly. // public static void main (String[] args) { final int MINOR = 21; Scanner scan = new Scanner (System.in); System.out.print ("Enter your age: "); int age = scan.nextInt(); continue

Copyright © 2012 Pearson Education, Inc. continue System.out.println ("You entered: " + age); if (age < MINOR) System.out.println ("Youth is a wonderful thing. Enjoy."); System.out.println ("Age is a state of mind."); } Sample Run Enter your age: 47 You entered: 47 Age is a state of mind. Another Sample Run Enter your age: 12 You entered: 12 Youth is a wonderful thing. Enjoy. Age is a state of mind.

Logical Operators What if we wanted to test for multiple conditions? For example, what if we want to print the temperature if it’s below 80 degrees and greater than 50 degrees? We use logical operators: if (temp 50) System.out.println(temp); Created by Emily Hill & Jerry Alan Fails

Logical Operators Boolean expressions can also use the following logical operators: ! Logical NOT && Logical AND || Logical OR They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands) Copyright © 2012 Pearson Education, Inc.

Logical NOT The logical NOT operation is also called logical negation or logical complement If some boolean condition a is true, then !a is false; if a is false, then !a is true Logical expressions can be shown using a truth table: Copyright © 2012 Pearson Education, Inc. a!a truefalse true

Logical AND and Logical OR The logical AND expression a && b is true if both a and b are true, and false otherwise The logical OR expression a || b is true if a or b or both are true, and false otherwise Copyright © 2012 Pearson Education, Inc.

Logical AND and Logical OR A truth table shows all possible true-false combinations of the terms Since && and || each have two operands, there are four possible combinations of conditions a and b Copyright © 2012 Pearson Education, Inc. aba && ba || b true false true falsetruefalsetrue false

Boolean Expressions Write an expression that evaluates to true if an integer variable age represents the age of a teenager (age >= 13 && age <= 19) Copyright © 2012 Pearson Education, Inc.

Boolean Expressions Write a statement that prints out “It’s fun to be a teen” if age represents the age of a teenager if (age >= 13 && age <= 19) System.out.println(“It’s fun to be a teen”); if (age > 12 && age < 20) System.out.println(“It’s fun to be a teen”); Copyright © 2012 Pearson Education, Inc.

Short-Circuited Operators The processing of && and || is “short-circuited” If the left operand is sufficient to determine the result, the right operand is not evaluated if (count != 0 && total/count > MAX) System.out.println ("Testing."); This type of processing is commonly used to avoid divide by zero and null pointer exceptions Copyright © 2012 Pearson Education, Inc.

Quick Check Copyright © 2012 Pearson Education, Inc. What do the following statements do? if (total != stock + warehouse) inventoryError = true; if (found || !done) System.out.println("Ok"); Sets the boolean variable to true if the value of total is not equal to the sum of stock and warehouse Prints "Ok" if found is true or done is false

Indentation The statement controlled by the if statement is indented to indicate that relationship The use of a consistent indentation style makes a program easier to read and understand The compiler ignores indentation, which can lead to errors if the indentation is not correct Copyright © 2012 Pearson Education, Inc.

Indentation Indentation is for the human reader, and is ignored by the compiler if (depth >= UPPER_LIMIT) delta = 100; else System.out.println("Reseting Delta"); delta = 0; Despite what the indentation implies, delta will be set to 0 no matter what Copyright © 2012 Pearson Education, Inc. "Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live." -- Martin Golding

Copyright © 2012 Pearson Education, Inc. //******************************************************************** // Wages.java Author: Lewis/Loftus // // Demonstrates the use of an if-else statement. //******************************************************************** import java.text.NumberFormat; import java.util.Scanner; public class Wages { // // Reads the number of hours worked and calculates wages. // public static void main (String[] args) { final double RATE = 8.25; // regular pay rate final int STANDARD = 40; // standard hours in a work week Scanner scan = new Scanner (System.in); double pay = 0.0; continue

Copyright © 2012 Pearson Education, Inc. continue System.out.print ("Enter the number of hours worked: "); int hours = scan.nextInt(); System.out.println (); // Pay overtime at "time and a half" if (hours > STANDARD) pay = STANDARD * RATE + (hours-STANDARD) * (RATE * 1.5); else pay = hours * RATE; NumberFormat fmt = NumberFormat.getCurrencyInstance(); System.out.println ("Gross earnings: " + fmt.format(pay)); } Sample Run Enter the number of hours worked: 46 Gross earnings: $404.25

Nested if Statements The statement executed as a result of an if or else clause could be another if statement Braces can be used to specify the if statement to which an else clause belongs An else clause is matched to the last unmatched if (no matter what the indentation implies) Copyright © 2012 Pearson Education, Inc.

Comparing Data Created by Emily Hill & Jerry Alan Fails

Comparing Float Values You might consider two floating point numbers to be "close enough" even if they aren't exactly equal Don’t use == when comparing real numbers ( float or double ), use a tolerance: if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal"); The tolerance could be set to any appropriate level, such as or even 0.01, depending on precision Copyright © 2012 Pearson Education, Inc.

Comparing Characters Characters can be compared like numbers, since internally they are encoded as numbers: For example: – ‘a’ + 1 => ‘b’‘A’ + 1 => ‘B’ – ‘a’ == ‘a’ => true Copyright © 2012 Pearson Education, Inc. CharactersUnicode Values 0 – 948 through 57 A – Z65 through 90 a – z97 through 122

Comparing Strings Remember a String is an object in Java, so we cannot use relational operators (==,, etc.) to compare strings (or objects) Instead, use the equals method: Or compareTo. For example, a call to name1.compareTo(name2) –returns zero if name1 and name2 are equal (contain the same characters) –returns a negative value if name1 is less than name2 –returns a positive value if name1 is greater than name2 if (name1.equals(name2)) System.out.println ("Same name"); Copyright © 2012 Pearson Education, Inc.

Comparing Strings Because comparing characters and strings is based on a character set, it is called a lexicographic ordering Copyright © 2012 Pearson Education, Inc. int result = name1.compareTo(name2); if (result < 0) System.out.println (name1 + "comes first"); else if (result == 0) System.out.println ("Same name"); else System.out.println (name2 + "comes first");

Lexicographic Ordering Lexicographic ordering is not strictly alphabetical when uppercase and lowercase characters are mixed For example, the string "Great" comes before the string "fantastic" because all of the uppercase letters come before all of the lowercase letters in Unicode Also, short strings come before longer strings with the same prefix (lexicographically) Therefore "book" comes before "bookcase" Copyright © 2012 Pearson Education, Inc.

Comparing Objects When applied to objects, == returns true if the two references are aliases of each other The equals method is defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the == operator It has been redefined in the String class to compare the characters in the two strings When you write a class, you can redefine the equals method to return true under whatever conditions are appropriate Copyright © 2012 Pearson Education, Inc.

Practice! Created by Emily Hill & Jerry Alan Fails

Part A: static methods tested in main Write a method that takes someone’s age as input and returns true if they can vote but not drink beer. (Note that you must be 18 to vote and 21 to drink.) Test in main Write a method isVowel that takes a character as input and returns whether or not the letter is a vowel. Test in main Write a method isVowel like above but taking a String as input instead of a character. Test in main Created by Emily Hill & Jerry Alan Fails

Part B: Timer class Create a Timer class that counts down from n to 0 (where n is specified by the constructor, 5 by default for the default constructor) You will need 2 fields: n & time_left Write a tick method that decrements the time left if time left is greater than zero, otherwise it prints: “You have no time left!” Created by Emily Hill & Jerry Alan Fails

Homework Finish this lab Work on CodingBat Finish Lab 7 Read Chapter 5 Created by Emily Hill & Jerry Alan Fails