0% found this document useful (0 votes)
13 views

Lecture04 Java

Chapter 4 of 'Starting Out with Java: Early Objects' covers decision structures in programming, including various types of if statements, nested if statements, if-else and if-else-if constructs, and the switch statement. It emphasizes the use of boolean expressions and provides examples of flowcharts to visualize decision-making processes. Additionally, the chapter discusses comparing string objects and the importance of using methods like equals and compareTo for string comparison.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Lecture04 Java

Chapter 4 of 'Starting Out with Java: Early Objects' covers decision structures in programming, including various types of if statements, nested if statements, if-else and if-else-if constructs, and the switch statement. It emphasizes the use of boolean expressions and provides examples of flowcharts to visualize decision-making processes. Additionally, the chapter discusses comparing string objects and the importance of using methods like equals and compareTo for string comparison.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Chapter 4:

Decision Structures

Starting Out with Java:


Early Objects

Fifth Edition

by Tony Gaddis
Chapter Topics
• The if Statement
• The if-else Statement
• Nested if statements
• The if-else-if Statement
• The switch Statement
• Comparing String Objects
• Variable Declaration and Scope
• The DecimalFormat Class

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-2
THE IF STATEMENT

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
The if Statement
• The if statement uses a boolean to decide
whether the next statement or block of
statements executes.

if (boolean expression is true)


execute next statement.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-4
Flowcharts
• If statements can be modeled as a flow chart.

if (coldOutside) Is it cold Yes


wearCoat(); outside?

Wear a coat.
No

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-5
Flowcharts
• A block if statement may be modeled as:

if (coldOutside)
{ Is it cold Yes
wearCoat(); outside?
wearHat(); Wear a coat.
wearGloves(); No
Wear a hat.
}
Wear gloves.
Note the use of curly
braces to block several
statements together.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-6
Boolean Expressions
• A boolean expression is any variable or calculation
that results in a true or false condition.

Expression Meaning
x > y Is x greater than y?
x < y Is x less than y?
x >= y Is x greater than or equal to y?
x <= y Is x less than or equal to y.
x == y Is x equal to y?
x != y Is x not equal to y?

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-7
if Statements and Boolean
Expressions
if (x > y)
System.out.println("X is greater than Y");

if(x == y)
System.out.println("X is equal to Y");

if(x != y)
{
System.out.println("X is not equal to Y");
x = y;
System.out.println("However, now it is.");
}

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-8
Programming Style and if Statements

• An if statement can span more than one line;


however, it is still one statement.
if (average > 95)
grade = ′A′;

is functionally equivalent to

if(average > 95) grade = ′A′;

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-9
Programming Style and if Statements
• Rules of thumb:
– The conditionally executed statement should be on
the line after the if condition.
– The conditionally executed statement should be
indented one level from the if condition.
– If an if statement does not have the block curly
braces, it is ended by the first semicolon
encountered after the if condition.
if (expression)
No semicolon here.
statement; Semicolon ends statement here.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-10
Block if Statements
• Conditionally executed statements can be grouped
into a block by using curly braces {} to enclose
them.
• If curly braces are used to group conditionally
executed statements, the if statement is ended by
the closing curly brace.
if (expression)
{
statement1;
statement2;
} Curly brace ends the statement.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-11
Block if Statements
• Remember that when the curly braces are not used,
then only the next statement after the if condition will
be executed conditionally.
if (expression)
statement1; Only this statement is conditionally executed.
statement2;
statement3;

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-12
FLAGS

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Flags
• A flag is a boolean variable that monitors some
condition in a program.
• When a condition is true, the flag is set to true.
• The flag can be tested to see if the condition has
changed.
if (average > 95)
highScore = true;
• Later, this condition can be tested:
if (highScore)
System.out.println("That′s a high score!");

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-14
IF-ELSE STATEMENTS

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
if-else Statements
• The if-else statement adds the ability to
conditionally execute code when the if
condition is false.
if (expression)
statementOrBlockIfTrue;
else
statementOrBlockIfFalse;

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-16
if-else Statement Flowcharts

No Yes
Is it cold
outside?

Wear shorts. Wear a coat.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-17
Exercise
• Write a Java program that uses the modulus operator
to determine if a number is odd or even. If the number
is evenly divisible by 2, it is an even number. A
remainder indicates it is odd.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-18
Exercise
• Write a Java program to compute and display a
person’s weekly salary as determined by the following
conditions: if the hours worked are less than or equal
to 40, the person receives $12.00 per hour; otherwise,
the person receives $480.00 plus $17.00 for each hour
worked over 40 hours. The program should request the
hours worked as input and display the salary as output.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-19
NESTED IF STATEMENTS

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Nested if Statements
• If an if statement appears inside another if
statement (single or block) it is called a nested
if statement.
• The nested if is executed only if the outer if
statement results in a true condition.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-21
Nested if Statement Flowcharts

No Yes
Is it cold
outside?

Wear shorts.
No Is it Yes
snowing?

Wear a jacket. Wear a parka.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-22
Nested if Statements
if (coldOutside)
{
if (snowing)
{
wearParka();
}
else
{
wearJacket();
}
}
else
{
wearShorts();
}

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-23
if-else Matching

• Curly brace use is not required if there is only


one statement to be conditionally executed.
• However, sometimes curly braces can help
make the program more readable.
• Additionally, proper indentation makes it much
easier to match up else statements with their
corresponding if statement.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-24
Alignment and Nested if Statements
if (coldOutside)
{
if (snowing)
{
This if and else wearParka();
go together.
This if and else }
go together. else
{
wearJacket();
}
}
else
{
wearShorts();
}

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-25
Exercise
• Write a banking program that determines whether a
bank customer qualifies for a special, low interest rate
on a loan. To qualify, two conditions must exist: (1)
the customer’s salary must be at least $50000, and (2)
the customer must have held his or her current job for
at least 2 years.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-26
IF-ELSE-IF STATEMENTS

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
if-else-if Statements
if (expression_1)
{
statement; If expression_1 is true these statements are
statement; executed, and the rest of the structure is ignored.
etc.
}
else if (expression_2)
{
statement; Otherwise, if expression_2 is true these statements are
statement;
etc. executed, and the rest of the structure is ignored.
}

Insert as many else if clauses as necessary

else
{
statement;
statement; These statements are executed if none of the
etc. expressions above are true.
}

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-28
if-else-if Statements
• The if-else-if statement makes certain
types of nested decision logic simpler to write.
• Nested if statements can become very
complex.
• Care must be used since else statements match up
with the immediately preceding unmatched if
statement.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-29
if-else-if Flowchart

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-30
Exercise
• The following table shows the approximate speed of sound in air,
water, and steel.
Medium Speed (feet per second)
Air 1100
Water 4900
Steel 16400

• Write a program that displays a menu allowing the user to select air,
water, or steel. After the user has made a selection, he or she should
be asked to enter the distance a sound wave will travel in the selected
medium. The program will then display the amount of time it will
take.
• Input validation: Check that the user has selected one of the
available choices from the menu. Do not accept distances less than 0.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-31
THE SWITCH STATEMENT

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
The switch Statement
• The if-else statement allows you to make
true / false branches.
• The switch statement allows you to use an
ordinal value to determine how a program will
branch.
• The switch statement can evaluate an integer
type or character type variable and make
decisions based on the value.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-33
The switch Statement
• The switch statement takes the form:
switch (SwitchExpression)
{
case CaseExpression:
// place one or more statements here
break;
case CaseExpression:
// place one or more statements here
break;

// case statements may be repeated


//as many times as necessary
default:
// place one or more statements here
}
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-34
The switch Statement
switch (SwitchExpression)
{

}

• The switch statement will evaluate the SwitchExpression,


which can be a byte, short, int, long, or char. If you are
using Java 7, the SwitchExpression can also be a string.

• If there is an associated case statement that matches that value,


program execution will be transferred to that case statement.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-35
The switch Statement
• Each case statement will have a corresponding
CaseExpression that must be unique.

case CaseExpression:
// place one or more statements here
break;

• If the SwitchExpression matches the CaseExpression,


the Java statements between the colon and the break
statement will be executed.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-36
The case Statement
• The break statement ends the case statement.
• If a case does not contain a break, then program
execution continues into the next case.
• The default section is optional and will be executed
if no CaseExpression matches the SwitchExpression.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-37
switch Flowchart

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-38
Exercise – Using switch
• The following table shows the approximate speed of sound in air,
water, and steel.
Medium Speed (feet per second)
Air 1100
Water 4900
Steel 16400

• Write a program that displays a menu allowing the user to select air,
water, or steel. After the user has made a selection, he or she should
be asked to enter the distance a sound wave will travel in the selected
medium. The program will then display the amount of time it will
take.
• Input validation: Check that the user has selected one of the
available choices from the menu. Do not accept distances less than 0.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-39
COMPARING STRING
OBJECTS

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Comparing String Objects
• In most cases, you cannot use the relational operators
to compare two String objects.
• Reference variables contain the address of the object
they represent. A String variable holds the memory
address of a String object.
• Unless the references point to the same object, the
relational operators will not return true.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-41
The String class’s equals method
• To determine whether two String objects are equal,
you should use the String class’s equals
method. The general form of the method is
StringReference1.equals(StringReference2)

• StringReference1 is a variable that references a


String object, and StringReference2 is
another variable that references a String object. The
method returns true if the two strings are equal, or
false if they are not equal. Here is an example:
If (name1.equals(name2))
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-42
The String class’s equals method
• To determine if two strings are not equal, simply apply
the ! operator to the equals method’s return value.
Here is an example:
If (!name1.equals(“Mark”))

• The boolean expression in this if statement


performs a not-equal-to operation. It determines
whether the object referenced by name1 is not equal
to “Mark”.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-43
The String class’s compareTo method
• The String class’s also provides the compareTo
method, which can be used to determine whether one
string is greater that, equal to, or less than another
string. The general form of the method is:
StringReference.compareTo(OtherString)

• StringReference is a variable that references a


String object, and OtherString is either another
variable that references a String object or a string
literal.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-44
The String class’s compareTo method
• The method returns an integer value that can be used
in the following manner:
– If the method’s return value is negative, the string referenced
by StringReference is less than the OtherString
argument.
– If the method’s return value is 0, the two strings are equal.
– If the method’s return value is positive, the string referenced
by StringReference is greater than the OtherString
argument.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-45
Ignoring Case in String Comparisons
• In the String class the equals and
compareTo methods are case sensitive.
• In order to compare two String objects that
might have different case, use:
– equalsIgnoreCase, or
– compareToIgnoreCase

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-46
Example: SecretWord.java

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-47
Example: SecretWord.java (continue)

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-48
VARIABLE SCOPE

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Variable Scope
• In Java, a local variable does not have to be declared at
the beginning of the method.
• The scope of a local variable begins at the point it is
declared and terminates at the end of the method.
• When a program enters a section of code where a
variable has scope, that variable has come into scope,
which means the variable is visible to the program.

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-50
THE DECIMALFORMAT CLASS

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
The DecimalFormat Class
• When printing out double and float values, the full
fractional value will be printed, which is usually more than
what we need.
– 15 digits for double
– 6 digits for float
• The DecimalFormat class can be used to format these
values.
• In order to use the DecimalFormat class, the following
import statement must be used at the top of the program:

import java.text.DecimalFormat;

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-52
The DecimalFormat Class
• To use the DecimalFormat class, you create an object:
DecimalFormat formatter = new DecimalFormat(“#0.00”);

“#0.00” is called a format pattern, where each character in the


format pattern corresponds with a position in a number.

# a single digit (if no digit at that position, nothing shown)


0 a single digit (if no digit at that position, 0 will be displayed)
.00 display 2 digits after decimal point

Note that if the number of characters before the decimal point is not
enough size to display to value, Java will automatically expand
the area.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-53
The DecimalFormat Class
• If format pattern is “#0.00”
0.1666 will be displayed as 0.17
166.6666 will be displayed as 166.67
• If format pattern is “#.00”
0.1666 will be displayed as .17
166.6666 will be displayed as 166.67
• If format pattern is “000.00”
0.1666 will be displayed as 000.17
166.6666 will be displayed as 166.67

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-54
The DecimalFormat Class
• Now call the format method on the DecimalFormat object
and pass the number you want to format as a parameter.
double n1 = 0.1666;
double n2 = 1.666;
double n3 = 16.666;
double n4 = 166.666;
System.out.println(formatter.format(n1));
System.out.println(formatter.format(n2));
System.out.println(formatter.format(n3));
System.out.println(formatter.format(n4));

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-55
The DecimalFormat Class
• If format pattern is “#,##0.00” with grouping separator
123.899 will be displayed as 123.90
1233.899 will be displayed as 1,233.90
1234567.899 will be displayed as 1,234,567.90
• If format pattern is “$#,##0.00” with $ at the beginning of
the pattern
12345.67 will be displayed as $12,345.67
• If format pattern is “0%” with % at the end of the pattern
0.12 will be displayed as 12%
0.05 will be displayed as 5%
0.005 will be displayed as 0%

©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 3-56
Chapter 4:
Decision Structures

Starting Out with Java:


Early Objects

Fifth Edition

by Tony Gaddis

You might also like