If Statement if (amount <= balance) balance = balance - amount;

Slides:



Advertisements
Similar presentations
DECISIONS Chapter 5. The if Statement  Action based on a conditions  If the condition is true, the body of the statement is executed if (amount
Advertisements

String and Object Comparison Comparison operator.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 6: Iteration 1 Chapter 6 Iteration.
Math 130 Decisions II Wed, Sept 12, 2007 Notes: ref. C. Horstmann, Java Concepts.
Chapter 5 – Decisions Big Java by Cay Horstmann
Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.
Computer Science A 4 13/3. Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Chapter 6 Iteration Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Chapter 5  Decisions 1 Chapter 5 Decisions. Chapter 5  Decisions 2 Chapter Goals  To be able to implement decisions using if statements  To understand.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Computer Science A 3: 10/2. Logical Expressions Expressions that has a value which is either true or false. Logical expressions are essential in a program.
Loops – While, Do, For Repetition Statements Introduction to Arrays
If Statement if (amount
Datalogi A 5: 6/10. while Loops Executes a block of code repeatedly A condition controls how often the loop is executed while (condition) statement; Most.
Chapter 5 – Decisions Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 6 Decisions. Chapter Goals To be able to implement decisions using if statements To understand how to group statements into blocks To learn how.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
The switch Statement, DecimalFormat, and Introduction to Looping
Chapter 5: Decisions. To be able to implement decisions using if statements To understand how to group statements into blocks To learn how to compare.
Chapter 6 - Decisions. Characters char char primitive data type primitive data type stores a single character stores a single character operations (same.
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Chapter 5 Decisions. Assignments  Written exercises pp 217 – 220 R5.1, R5.3, R5.5, R5.6, R5.9 – R5.15, R5.17, R R5.1, R5.3, R5.5, R5.6, R5.9 –
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. if (amount
Decisions CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 5, Horstmann*
Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester,
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 3:Decision Structures.  3.1 The if Statement  3.2 The if-else Statement  3.3 The if-else-if Statement  3.4 Nested if Statements  3.5 Logical.
Flow of Control Part 1: Selection
 Executes a block of code repeatedly  A condition controls how often the loop is executed  Most commonly, the statement is a block statement (set of.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 5: Decisions 1 Chapter 5 Decisions.
Fall 2006Slides adapted from Java Concepts companion slides1 Decisions Advanced Programming ICOM 4015 Lecture 5 Reading: Java Concepts Chapter 6.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
1 Chapter 4: Basic Control Flow ► Chapter Goals  To be able to implement decisions using if statements  To understand statement blocks  To learn how.
1-Dec-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Week 7 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Chapter 6 Decisions. Chapter Goals To be able to implement decisions using if statements To understand how to group statements into blocks To learn how.
Week 7 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 6 Iteration. Chapter Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To.
Decisions Bush decision making.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Decision Statements, Short- Circuit Evaluation, Errors.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Chapter 7 Iteration. Chapter Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To.
Java Programming Fifth Edition
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
The switch Statement, and Introduction to Looping
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Chapter 4: Making Decisions.
Chapter 5/6 Decisions.
Selected Topics From Chapter 6 Iteration
Control Structure Chapter 3.
Chapter 5 – Decisions Big Java by Cay Horstmann
Chapter 2 Programming Basics.
Repetition Statements (Loops) - 2
Control Structure.
Presentation transcript:

if Statement if (amount <= balance) balance = balance - amount;

if/else Statement if (amount <= balance) balance = balance - amount; else balance = balanceOVERDRAFT_PENALTY;

Block Statement if (amount <= balance) { double newBalance = balance - amount; balance = newBalance; } Note: block allows more than one ‘statement’ to be combined, to form a new ‘statement’

Equality Testing vs. Assignment  The = = operator tests for equality: if (x = = 0).. // if x equals zero  The = operator assigns a value to a variable: x = 0; // assign 0 to x  Don't confuse them.  Java = = is the same as mathematical =

Comparing Floating-Point Numbers  Consider this code: double r = Math.sqrt(2); double d = r * r -2; if (d == 0) System.out.println( "sqrt(2)squared minus 2 is 0"); else System.out.println( "sqrt(2)squared minus 2 is not 0 but " + d);

 It prints: sqrt(2)squared minus 2 is not 0 but E-16  Don't use == to compare floating-point numbers

Comparing Floating-Point Numbers  Two numbers are close to another if |x - y| <= ε  ε is a small number such as  Not good enough if x, y very large or very small. Then use |x - y| / max(|x|, |y|) <= ε  But if one of the numbers is zero, don't divide by max(|x |, |y|)

String Comparison  Don't use = = for strings! if (input = = "Y") // WRONG!!!  Use equals method: if (input.equals("Y"))  = = tests identity, equals tests equal contents  Case insensitive test ("Y" or "y") if (input.equalsIgnoreCase("Y"))

Lexicographic Comparison  s.compareTo(t) < 0 means: s comes before t in the dictionary  "car"comes before "cargo" "cargo" comes before "cathode"  All uppercase letters come before lowercase: "Hello" comes before "car"

Lexicographic Comparison

Object Comparison  = = tests for identical object  equals for identical object content  Rectangle cerealBox = new Rectangle(5, 10, 20, 30); Rectangle oatmealBox = new Rectangle(5, 10, 20, 30); Rectangle r = cerealBox;  cerealBox != oatmealBox, but cerealBox.equals(oatmealBox)  cerealBox == r Caveat: equals must be defined for the class (chap 11)

Object Comparison

The null Reference  null reference refers to no object at all  Can be used in tests: if (account == null)...  Use ==, not equals, to test for null  showInputDialog returns null if the user hit the cancel button: String input = JOptionPane.showInputDialog("..."); if (input != null) {... }  null is not the same as the empty string ""

Multiple Alternatives if (condition1) statement1; else if (condition2) statement2; else if (condition3) statement3; else statement4; The first matching condition is executed. Order matters.

Multiple Alternatives  Order matters: if (condition1) Statement1; else if (condition2) Statement2; else if (condition3) Statement3; else // option – executes of all conditions fail Statement4;

Nested Branches Branch inside another branch if (condition1) { if (condition1a) statement1a; else statement1b; } else statement2;

The boolean Type  George Boole ( ): pioneer in the study of logic  value of expression amount < 1000 is true or false.  boolean type: set of 2 values, true and false

Predicate Method  return type boolean  Example: public boolean isOverdrawn() { return balance < 0; }  Use in conditions if (harrysChecking.isOverdrawn())...  Useful predicate methods in Character class: isDigit isLetter isUpperCase isLowerCase  if (Character.isUpperCase(ch))...

Boolean Operators  ! not  && and (short circuited)  || or (short circuited)

Truth Tables

Boolean Variables  private boolean married;  Set to truth value: married = input.equals("M");  Use in conditions: if (married)... else... if (!married)...  Also called flag  Don't test Boolean variables against truth values-- sign of cluelessness: if (married == true) // DON'T if (married == false) // DON'T if (married != false) // NO!!!

Investment with Compound Interest Invest $10,000, 5% interest, compounded annually When will the balance be at least $20,000?

while Statement while (condition) statement; //repeats the statement while the condition is true while (balance < targetBalance){ year++; double interest = balance * rate / 100; balance = balance + interest; }

Flowchart for while Loop

Common Error: Infinite Loop while (year < 20) { balance = balance + balance * rate / 100; } while (year > 0) { year++; // oops, meant -- } Loops run forever--must kill program

Common Error: Off-by-1 Error year = 0; while (balance < targetBalance){ year++; double interest = balance * rate / 100; balance = balance + interest; } System.out.println("Reached target after " + year + " years.");  Should year start at 0 or 1?  Should the test be < or <=?

Avoiding Off-by-1 Error  Run through a simple example: target balance = $20,000, interest rate 50% after one year: balance = $15,000 after two years: balance = $22,500 Therefore: year must start at 0  interest rate 100% after one year: balance = $20,000 loop should stop Therefore: must use <  Think, don't compile and try at random

do Statement Executes loop body at least once: do statement while (condition); Example: Validate input double value; do{ String input = JOptionPane.showInputDialog( "Please enter a positive number"); value = Integer.parseInt(input); } while (input <= 0);

Flowchart for do Loop

for (initialization; condition; update) statement  Example: for (int i = 1; i <= n; i++){ double interest = balance * rate / 100; balance = balance + interest; }  Equivalent to: initialization; while (condition){ statement; update; } for Statement

Flowchart for for Loop

Common Errors: Semicolons A semicolon that shouldn't be there sum = 0; for (i = 1; i <= 10; i++); sum = sum + i; System.out.println(sum);

Common Errors: Semicolons A semicolon that shouldn't be there sum = 0; i = 1; while ( i <= 10) ; { sum = sum + i; i = i + 1; } System.out.println(sum);

Nested Loops  Create triangle pattern [] [][] [][][] [][][][]  Loop through rows for (int i = 1; i <= n; i++) { // make triangle row }

 Make triangle row is another loop for (int j = 1; j <= i; j++) r = r + "[]"; r = r + "\n";  Put loops together => Nested loops for (int i = 1; i <= width; i++) { // make triangle row for (int j = 1; j <= i; j++) r = r + "[]"; r = r + "\n"; }

Reading Input Values General pattern: boolean done = false; while (!done) { String input = read input; if (end of input indicated) done = true; else { process input } } "Loop and a half"

Another option… General pattern: while (end of input != read input ){ process input }

String Tokenization  StringTokenizer breaks up string into tokens  By default, white space separates tokens  " " breaks into three tokens: "4.3", "7", "-2" StringTokenizer tokenizer = new StringTokenizer(a String); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); process token }

Traversing Characters in String s.charAt(i) is the ith character of the string s for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); process ch }