The if Statement

Download Report

Transcript The if Statement

Chapter 5: Conditionals and Loops
• Topics:
– Boolean expressions
– Conditional statements
– Increment and Decrement Operators (Chapter
2.4)
– Repetition statements
– the Random class (Chapter 3.4)
– Comparing Strings
5-1
Flow of Control
• The order of statement execution is called
the flow of control
• Unless specified otherwise, the order of
statement execution through a method is
linear: one statement after another in
sequence
5-2
Flow of Control
• Some programming statements allow us to:
– decide whether or not to execute a particular
statement
– execute a statement over and over, repetitively
• These decisions are based on boolean
expressions (or conditions) that evaluate to true
or false
– For example, num > 5
5-3
Conditional Statements
• A conditional statement lets us choose
which statement will be executed next
• The Java conditional statements are the:
– if statement
– if-else statement
– switch statement
5-4
The if Statement
• The if statement has the following syntax:
if is a Java
reserved word
The condition must be a
boolean expression. It must
evaluate to either true or false.
if ( condition )
statement;
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
5-5
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.");
}
}
5-6
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
5-7
Equality Operator and Assignment Operator
• Note the difference between the equality
operator (==) and the assignment operator (=)
• num == 4 is a comparison: the boolean
expression has the value true or false
• num = 4 is an assignment: the expression has
the value 4 because that’s the value of the left
side
5-8
A Mistake You’ll Probably Make
• What if you accidentally drop an equals sign in the
boolean expression?
int num = 5;
if (num = 4)
System.out.println("Hello");
• You will get a “incompatible types” error:
found
: int
required: boolean
5-9
The if Statement
• An if statement lets a program decide whether a
particular statement is executed.
if (sum > MAX)
delta = sum - MAX;
System.out.println ("The sum is " + sum);
• 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.
• Either way, the call to println is executed next
5-10
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
• Although it makes no difference to the
compiler, proper indentation is crucial
5-11
Indentation
• Remember that indentation is for the
human reader, and is ignored by the
computer
if (total > MAX)
System.out.println ("Error!!");
errorCount++;
Despite what is implied by the indentation, the
increment will occur whether the condition is
true or not
5-12
The if Statement
• The precedence of the arithmetic operators
is higher than the precedence of the
equality and relational operators
if (total != stock + warehouse)
inventoryError = true;
Sets a flag to true if the value of total is not equal to
the sum of stock and warehouse
5-13
The if-else Statement
• An else clause can be added to an if
statement to make an 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
5-14
//********************************************************************
// 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
5-15
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));
}
}
5-16
Logic of an if-else statement
condition
evaluated
true
false
statement1
statement2
5-17
Exercise
• Write an if/else statement that compares
the variable age with 65 , adds 1 to the
variable seniorCitizens if age is greater
than or equal to 65 , and adds 1 to the
variable nonSeniors otherwise
5-18
Block Statements
• Keep in mind that the two alternatives in an
if else statement must be single
statements.
• If you need more than one statement for if
or else, you must use braces to collect
them into a single block statement.
5-19
Block Statements
• The following code produces a compiler error:
if (total > MAX)
System.out.println ("Error!!");
errorCount++;
else
System.out.println ("Total: " + total);
current = total*2;
• The compiler sees it as a simple if statement that ends
with the println ("Error!!"); statement. Then there is a
errorCount++ statement. But then there is what the
compiler perceives as an unattached else, and that is
flagged as a syntax error.
5-20
Block Statements
• Convert the code to what we want by
adding braces
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}
else
{
System.out.println ("Total: " + total);
current = total*2;
}
5-21
Exercise
• Modify the Ideal Weight (from lab 2)
program so it will not compute the ideal
weight if the height is less than 5 feet and
print a message.
5-22
Nested if Statements
• The statement executed as a result of an
if statement or else clause could be
another if statement
• These are called nested if statements
if (num1 > num2)
System.out.println ("greater");
else
{
if (num1 == num2)
System.out.println ("same");
else
System.out.println ("less");
}
5-23
Nested if Statements
• An else clause is matched to the last
unmatched if (no matter what the
indentation implies)
• Braces can be used to specify the if
statement to which an else clause belongs
5-24
Exercise
• Read in three integers from the user and
determine the minimum.
5-25
Repetition Statements
• Repetition statements allow us to execute a
statement multiple times. Often they are referred
to as loops
• Java has three kinds of repetition statements:
– the while loop
– the do loop
– the for loop
• The programmer should choose the right kind of
loop for the situation
5-26
Assignment Revisited
• The right and left hand sides of an
assignment statement can contain the
same variable First, one is added to the
original value of count
count
=
count + 1;
Then the result is stored back into count
(overwriting the original value)
5-27
Increment and Decrement
• The increment operator (++) adds one to its
operand
• The decrement operator (--) subtracts one
from its operand
• The statement
count++;
is functionally equivalent to
count = count + 1;
5-28
Increment and Decrement
• The increment and decrement operators can be
applied in postfix form:
count++
count --
• or prefix form:
++count
--count
• Postfix and prefix are functionally equivalent
when used alone in a statement, for example,
count currently contains the value 5, the two
increment statements assign 6 to count.
5-29
Increment and Decrement
• When used as part of a larger
expression, the two forms can have
different effects, for example, count
currently contains the value 5,
– Postfix:
• total = count ++; // assign 5 to total and 6 to
count
– Prefix:
• total = ++count; // assign 6 to total and 6 to
count
5-30
Exercises
• Given an integer variable
strawsOnCamel , write a statement that
uses the increment operator to increase
the value of that variable by 1
• Given an integer variable timer , write a
statement that uses the decrement
operator to decrease the value of that
variable by 1
5-31
The while Statement
• A while statement has the following syntax:
while ( condition )
statement;
• If the condition is true, the statement is
executed
• Then the condition is evaluated again, and if it is
still true, the statement is executed again
• The statement is executed repeatedly until the
condition becomes false
5-32
Logic of a while Loop
condition
evaluated
true
false
statement
5-33
The while Statement
• An example of a while statement:
int count = 1;
while (count <= 5)
{
System.out.println (count);
count++;
}
• If the condition of a while loop is false initially, the
statement is never executed
• Therefore, the body of a while loop will execute
zero or more times
5-34
Exercise
• What output is produced by the following
code fragment?
int num = 0, max = 20;
while (num < max)
{
System.out.println(num);
num +=4;
}
5-35
//********************************************************************
// Average.java
Author: Lewis/Loftus
//
// Demonstrates the use of a while loop, a sentinel value, and a
// running sum.
//********************************************************************
import java.text.DecimalFormat;
import java.util.Scanner;
public class Average
{
//----------------------------------------------------------------// Computes the average of a set of values entered by the user.
// The running sum is printed as the numbers are entered.
//----------------------------------------------------------------public static void main (String[] args)
{
int sum = 0, value, count = 0;
double average;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter an integer (0 to quit): ");
value = scan.nextInt();
continue
5-36
Copyright © 2012 Pearson Education, Inc.
continue
while (value != 0)
{
count++;
// sentinel value of 0 to terminate loop
sum += value;
System.out.println ("The sum so far is " + sum);
System.out.print ("Enter an integer (0 to quit): ");
value = scan.nextInt();
}
continue
5-37
continue
System.out.println ();
if (count == 0)
System.out.println ("No values were entered.");
else
{
average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat ("0.###");
System.out.println ("The average is " + fmt.format(average));
}
}
}
5-38
Exercise: Input Validation
• Modify the Ideal Weight program. If the
user enters a number less than 5 for feet,
the program should print an error message
and keep asking for another input.
5-39
Infinite Loops
• The body of a while loop eventually must make
the condition false
• If not, it is called an infinite loop, which will
execute until the user interrupts the program
• This is a common logical error
• You should always double check the logic of a
program to ensure that your loops will terminate
normally
5-40
Infinite Loops
• An example of an infinite loop:
int count = 1;
while (count <= 25)
{
System.out.println (count);
count = count - 1;
}
• This loop will continue executing until interrupted
(Control-C) or until an underflow error occurs
5-41
The Random Class
5-42
The Random Class
• The Random class is part of the java.util
package
• It provides methods that generate
pseudorandom numbers, for example, to
simulate a card shuffler.
• A Random object performs complicated
calculations based on a seed value to produce a
stream of seemingly random values
5-43
The Random Class
• Random ()
– Creates a new pseduorandom number generator.
– Random generator = new Random();
• Method:
int nextInt (int num)
– Returns a random number in the range 0 to num -1.
5-44
Random Floating Point
• float nextFloat ()
– Returns a random number between 0.0
(inclusive) and 1.0 (exclusive).
5-45
//********************************************************************
// RandomNumbers.java
Author: Lewis/Loftus
//
// Demonstrates the creation of pseudo-random numbers using the
// Random class.
//********************************************************************
import java.util.Random;
public class RandomNumbers
{
//----------------------------------------------------------------// Generates random numbers in various ranges.
//----------------------------------------------------------------public static void main (String[] args)
{
Random generator = new Random();
int num1, num2;
num1 = generator.nextInt(10);
System.out.println ("From 0 to 9: " + num1);
continued
5-46
Copyright © 2012 Pearson Education, Inc.
continued
num1 = generator.nextInt(10) + 1;
System.out.println ("From 1 to 10: " + num1);
num1 = generator.nextInt(15) + 20;
System.out.println ("From 20 to 34: " + num1);
num1 = generator.nextInt(20) - 10;
System.out.println ("From -10 to 9: " + num1);
num2 = generator.nextFloat();
System.out.println ("A random float (between 0-1): " + num2);
num2 = generator.nextFloat() * 6; // 0.0 to 5.999999
num1 = (int)num2 + 1;
System.out.println ("From 1 to 6: " + num1);
}
}
5-47
Copyright © 2012 Pearson Education, Inc.
Exercise
• Write a program that simulates the rolling
of a pair of dice. For each die in the pair,
the program should generate a random
number between 1 and 6 (inclusive).
• It should print out the result of the roll for
each die and the total roll (the sum of the
two dice)
5-48
Comparing Strings
• Remember that in Java a character string is an object
• The equals method can be called with strings to
determine if two strings contain exactly the same
characters in the same order
• The equals method returns a boolean result
if (name1.equals(name2))
System.out.println ("Same name");
else
System.out.println(“Not same”);
5-49
Exercise
• Modify the rolling dice program so it allows
the user to keep rolling the dice as long as
the user enters "yes".
5-50
Other Repetition Statements: The do
Statement
5-51
The do Statement
• A do statement has the following syntax:
do
{
statement;
}
while ( condition );
There is a semicolon
• The statement is executed once initially, and then
the condition is evaluated
• The statement is executed repeatedly until the
condition becomes false
5-52
Comparing while and do
The while Loop
The do Loop
statement
condition
evaluated
true
statement
true
false
condition
evaluated
false
5-53
The do Statement
• An example of a do loop:
int count = 0;
do
{
count++;
System.out.println (count);
} while (count < 5);
• The body of a do loop executes at least once
5-54
Exercise
• Write a program that computes the reverse
number of a number entered by the user. For
example, the reverse number of 8352 is 2538.
5-55
Readings and Assignments
• Reading: Chapter 5.1-5.4, 2.4, 3.4
• Lab Assignment: Java Lab 4
• Self-Assessment Exercises:
– Self-Review Questions Section
• SR5.8, 5.11, 5.18, 5.21
– After Chapter Exercises
• EX 5.2, 5.4, 5.8, 5.9
5-56