CS 46A - Lecture 11

Cover page image

Pre-class reading

The if Statement

The if/else Statement

if (amount <= balance)
   balance = balance - amount;
else
   balance = balance - OVERDRAFT_PENALTY;

Statement Types

Syntax 5.1 The if Statement

Syntax 5.1 if Statement

Comparing Values: Relational Operators

Lecture 11 Clicker Question 1

Consider the code fragment that is intended to fix the withdraw method so that the account balance can't be negative.

public void withdraw(double amount)
{
   if (amount <= balance) // Make sure the account isn't overdrawn
      newBalance = balance - amount; 
      balance = newBalance;
}

What is wrong with this code?

  1. It should be <, not <=
  2. It should be >=, not <=
  3. It should be >, not <=
  4. Something else

Comparing Floating-Point Numbers

Comparing Floating-Point Numbers

Comparing Strings

Comparing Strings

Lexicographic Comparison

Syntax 5.2 Comparisons

Syntax 5.2 Comparisons

Comparing Objects

Object Comparison

Testing for null

Relational Operator Examples

Relational Operator Examples

Lecture 11 Clicker Question 2

Consider the following definitions.

String a = "1";
String b = "one";
double x = 1;
double y = 3 * (1.0 / 3);

How many of the following comparisons are syntactically incorrect? How many of them are syntactically correct, but logically questionable?

  1. Two incorrect, two questionable
  2. Two incorrect, three questionable
  3. Three incorrect, two questionable
  4. Three incorrect, three questionable