of 111
7/30/2019 Computer Science 1302
1/111
11
Chapter 3
DECISION STRUCTURES
7/30/2019 Computer Science 1302
2/111
22
THE ifSTATEMENT
The ifstatement allows us to specify the condition under which a
statement or block of statements is to be executed.
The general form of the ifstatement is as follows:
if (Boolean expression){
statement(s);}
The keyword ifis followed by a parenthesized Boolean
expression. If this conditional expression is true, the
statement(s) in the block that follows are executed. The
statement(s) in the block are skipped if the Boolean expression is
alse.
7/30/2019 Computer Science 1302
3/111
33
THE ifSTATEMENT
Using Relational Operators to Form Boolean
ExpressionsFrequently, the Boolean expression used as the test in an if
statement is formed using a relational operator.
A relational operator tests whether a particular relationshipexists between its operands.
*** See Table 3-1 of the text
7/30/2019 Computer Science 1302
4/111
44
THE ifSTATEMENT
Using Relational Operators to Form Boolean
Expressions
is not equal to!=
is equal to==
is less than or equal to=
is less than
MeaningRelational Operator
7/30/2019 Computer Science 1302
5/111
55
THE ifSTATEMENT
Using Relational Operators to Form Boolean
Expressions
All of the relational operators are binary operators, meaningthey take two operands.
The relational operators have lower precedence than the
arithmetic operators *, /, %, +, and , but higher precedencethan the assignment operators (including the combinedassignment operators).
The relational operators associate from left to right.
*** See Appendix C of the text
7/30/2019 Computer Science 1302
6/111
66
THE ifSTATEMENT
Using Relational Operators to Form Boolean
ExpressionsGiven that the variables a and b have the values specified at the
left, fill in the table showing the values of the expressions given.
Values of variables Expression Value?
int a = 5, b = 6 b < adouble a = 8.9, b = 4.2 a > bint a = 10, b = 12 a = Z
int a = 5, b = 6, c = 4 a * c != (b + c) * 2
7/30/2019 Computer Science 1302
7/111
77
THE ifSTATEMENT
The statement below specifies that five is to be added to t
only ifx is greater than zero.
if(x > 0){
t += 5;}
Notice that there is not a semicolon after the parenthesized
Boolean expression. Remember that semicolons mark the
end of a statement, not the end of a line. A complete if
statement includes a conditionally executed statement or
block.
7/30/2019 Computer Science 1302
8/111
88
THE ifSTATEMENT
If you accidentally put a semicolon after the conditional
expression, the compiler will think that the conditionally
executed statement is the null statement. The null statement
is an empty statement that does nothing.
if (x > 0);{
t += 5;}
The semicolon disconnects the statement t += 5; from the if;it is no longer conditionally executed. Five will always be
added to tregardless of the value ofx.
Putting a semicolon here is a
logical error
7/30/2019 Computer Science 1302
9/111
99
THE ifSTATEMENT
Programming Style for ifStatements
When writing a ifstatement:
Begin the conditionally executed statement or block on
the line below the if (Boolean expression). Indent the conditionally executed statement(s) one level
from the key word if.
if(x > 0){
t += 5;}
7/30/2019 Computer Science 1302
10/111
1010
THE ifSTATEMENT
Flowchart for ifStatement
if(x > 0){
t += 5;}
x > 0
false
true
t = t + 5
7/30/2019 Computer Science 1302
11/111
1111
THE ifSTATEMENT
The following statement specifies that the messageError:
Invalid weight entered. is to be displayed on a line on the
computer screen only ifweightis less than or equal to zero.
if (weight
7/30/2019 Computer Science 1302
12/111
1212
THE ifSTATEMENT
The following statement specifies that senioris to beassigned the value true ifage is greater than or equal tosixty-two.
senior = false;
if(age >=62){
senior = true;}
7/30/2019 Computer Science 1302
13/111
7/30/2019 Computer Science 1302
14/111
1414
THE ifSTATEMENT
Without the braces, the value of the conditional expression
controls only the execution of the statement that
immediately follows it.
It is recommended that you enclose a single conditionallyexecuted statement in braces. Without the braces, if another
statement is inserted between the conditional expression and
the conditionally executed statement the second statementisdisconnected from the conditional expression and will
execute regardless of the value of conditional expression.
7/30/2019 Computer Science 1302
15/111
1515
THE ifSTATEMENT
The statement below specifies that if the value of the variable ch1 is equal to the
character S, the following actions are to be taken in the order given:
1. The value of the variable i is to be multiplied by .15 and the result obtained isassigned to the variablex.
2. The value in the variablez is to be reduced by the value in the variablex.3. 10000 is to be added to the value of the variablez and the resulting value is to
be assigned to the variabley
4. The value of the variabley is to be displayed on the computer screen after themessage y is .
if(ch1 == 'S'){
x = i * .15;z -= x;y = z + 10000;System.out.println("y is " + y);
}
7/30/2019 Computer Science 1302
16/111
1616
THE ifSTATEMENT
If you forget the braces, the conditionally executed statement is x = i * .15.The other statements are executed regardless of the value ofch1. The
indentation is for the human reader. The compiler ignores spaces, tabs, and
newlines that are not inside quotation marks.
if(ch1 == 'S')x = i * .15;z -= x;y = z + 10000;System.out.println("y is " + y);
is equivalent to:
if(ch1 == 'S')x = i * .15;
z -= x;y = z + 10000;
System.out.println("y is " + y);
7/30/2019 Computer Science 1302
17/111
1717
THE if/else STATEMENT
If we want one set of statements to be executed if a condition is true
and another set of statements to be executed if the condition isfalse,
we can use an if/else statement.
The general form of an if/else statement is as follows:
if (Boolean expression){
// if block
statement(s);}else{
// else block
statement(s);
}
7/30/2019 Computer Science 1302
18/111
1818
THE if/else STATEMENT
The parenthesized conditional expression following the key word ifis evaluated. Ifthe expression evaluates to true, the statement(s) in the ifblock are executed andthen execution continues with the statement that follows the else block. If theconditional expression isfalse, the statement(s) in the else block are executed andthen execution continues with the statement that follows the else block
if (Boolean expression){
// if block
statement(s);}else{
// else block
statement(s);}
7/30/2019 Computer Science 1302
19/111
1919
THE if/else STATEMENT
The following statement specifies that as long as denominatoris notequal to 0.0 the division is to be performed and the result of thedivision is to be displayed on the computer screen. If however,denominatoris equal to 0.0, the error messageError: cannot divide
by zero. is to be displayed on the computer screen.
if(denominator != 0.0){
result = numerator / denominator;System.out.println(numerator + " / " + denominator + " is " + result);
}else{
System.out.println("\nError: cannot divide by zero.");}
7/30/2019 Computer Science 1302
20/111
2020
THE if/else STATEMENT
Division by Zero
Programmers must write code to guard against division by zero.
Dividing by zero is a logical error. Dividing an integer by the
integer zero, causes a program to terminate/crash.
if(denominator != 0.0)
{result = numerator / denominator;System.out.println(numerator + " / " + denominator + " is " + result);
}else{
System.out.println("\nError: cannot divide by zero.");}
7/30/2019 Computer Science 1302
21/111
2121
THE if/else STATEMENT
Notice that there is not a semicolon after the parenthesized Booleanexpression or the key word else in an if/else statement.
When a single statement is to be conditionally executed the braces
can be omitted. Again, this is not recommended.
if(denominator != 0.0){
result = numerator / denominator;System.out.println(numerator + " / " + denominator + " is " + result);
}else{
System.out.println("\nError: cannot divide by zero.");}
There should not be semicolons here!
7/30/2019 Computer Science 1302
22/111
2222
THE if/else STATEMENT
It is good programming style to have the else corresponding to an ifat thesame level of indentation. In addition, the block that is executed if theconditional expression is true should begin on the line below theconditional expression and the statements should be indented one levelfrom the key word if. The block that is executed if the conditional
expression isfalse should begin on the line below the key word else and thestatements in this block should be indented one level from the key wordelse.
if(denominator != 0.0){
result = numerator / denominator;System.out.println(numerator + " / " + denominator + " is " + result);
}else{
System.out.println("\nError: cannot divide by zero.");
}
7/30/2019 Computer Science 1302
23/111
2323
THE if/else STATEMENT
Flowchart for if/else Statement
if(denominator != 0.0){
result = numerator / denominator;System.out.println(numerator + " / " + denominator + " is " + result);
}else{
System.out.println("\nError: cannot divide by zero.");
}
denominator!= 0.0
false true
result = numerator /denominator
Display anerror message
Display theresult
7/30/2019 Computer Science 1302
24/111
24
*** See the program CircleAreaWInputValid.java which isavailable on webct.
7/30/2019 Computer Science 1302
25/111
25
Problem:
Write a program to calculate and display the gross pay of anhourly employee for one week. For time worked over forty
hours the employee is paid at 1 times his/her normal hourly
pay rate.
7/30/2019 Computer Science 1302
26/111
26
Beginning the analysis of the problem, the programmer might
try to list the purpose, inputs, processing, and outputs of the
program to clarify the problem.
Purpose To calculate and display an hourly employees weekly gross
pay
Inputs Number of hours worked, hourly pay rate
Processing Multiply the number of hours worked less than or equal to forty
hours by the hourly pay rate to find the regular pay. Multiply
the hours worked over forty hours by 1 times the pay rate to
find overtime pay. The gross pay is the regular pay plus the
overtime pay.
Output Display a message indicating the gross pay for the employee
7/30/2019 Computer Science 1302
27/111
27
Next, the programmer might use a tool such as pseudocode or a
flowchart to develop an algorithm to solve the problem.
Sample pseudocode for the problem defined above:
Get the hours worked
Get the hourly pay rate
Set overtime pay to zero
If the number of hours worked is less than or equal to forty
Multiply hours worked by the pay rate to find regular pay
Else
Multiply forty by the pay rate to find regular pay
Multiply the difference between hours worked and forty by 1 times the
pay rate to find overtime pay
Add regular pay and overtime pay to find gross payDisplay the gross pay
7/30/2019 Computer Science 1302
28/111
28
Sample flowchart for the problem defined above:START
Get hours
worked
Get hourly
pay rate
Set overtime pay to zero
Display gross
pay
hours
worked
7/30/2019 Computer Science 1302
29/111
29
Remember part of the design process is the design of the test
plan.
7/30/2019 Computer Science 1302
30/111
30
Sample test plan for the problem defined above:
Inputs Expected Output Value
Hours worked = 40Hourly pay = 10 $400.00
Hours worked = 41Hourly pay = 20.00 $830.00
Hours worked = 0Hourly pay = 25.00 $0.00
Hours worked = 10Hourly pay = 7.55 $75.50
Hours worked = 29.75Hourly pay = 10.23 $304.34
Hours worked = 50.5Hourly pay = 20.48 $1141.76
Hours worked = 40Hourly pay = 0 Error
Hours worked = 38.5
Hourly pay = -10.00 Error
Hours worked = - 40Hourly pay = 5.00 Error
Hours worked = 168Hourly pay = 8.30 $1925.60
Hours worked = 169
Hourly pay = 10.00 Error
7/30/2019 Computer Science 1302
31/111
31
*** See the program CalculateGrossPay.java on webct.
7/30/2019 Computer Science 1302
32/111
3232
THE if/else ifSTATEMENT
We can create a mutli-way decision structure by constructing a chain ofif/else statements.
7/30/2019 Computer Science 1302
33/111
3333
THE if/else ifSTATEMENT
Typically this type of decision is written as follows:
if (Boolean expression){
statement(s)
}else if (Boolean expression){
statement(s)}else if (Boolean expression) // Include as many else ifs as needed to encode alternatives{
statement(s)}else{
statement(s)}
7/30/2019 Computer Science 1302
34/111
3434
THE if/else ifSTATEMENT
if (Boolean expression){
statement(s)}else if (Boolean expression){
statement(s)
}else if (Boolean expression) // Include as many else ifs as needed to encode alternatives{
statement(s)}else{
statement(s)
}
When you chain the if/elses in this way, the second ifis actually in the else portion ofthe first if/else; the third ifis actually in the else portion of the second if/else statement
7/30/2019 Computer Science 1302
35/111
3535
THE if/else ifSTATEMENT
if (Boolean expression){
statement(s)}else if (Boolean expression){
statement(s)
}else if (Boolean expression) // Include as many else ifs as needed to encode alternatives{
statement(s)}else{
statement(s)
}
When this type of statement is executed, the various conditional expressions are evaluated inorder, from top to bottom, until the first, if any, that evaluates to true is found. The conditionallyexecuted statement or block that follows the first true expression is executed and then executioncontinues after the last conditionally executed statement. Execution will only get to a particularconditional expression, if all the previous conditional expressions arefalse.
7/30/2019 Computer Science 1302
36/111
3636
THE if/else ifSTATEMENT
if (Boolean expression){
statement(s)}else if (Boolean expression){
statement(s)
}else if (Boolean expression) // Include as many else ifs as needed to encode alternatives{
statement(s)}else{
statement(s)
}
The trailing else is optional, it can be used to specify what is to be done if
none of the conditional expressions are true.
7/30/2019 Computer Science 1302
37/111
3737
THE if/else ifSTATEMENT
if (Boolean expression){
statement(s)}else if (Boolean expression){
statement(s)
}else if (Boolean expression) // Include as many else ifs as needed to encode alternatives{
statement(s)}else{
statement(s)
}
We use a special indentation style to encode a multi-way decision. Noticethat in this case we are not lining up an else with its associated if. We aredoing this to visually convey that we have a multi-way decision not a decisionbetween two alternatives.
7/30/2019 Computer Science 1302
38/111
38
*** See the programAssignGrades.java
The first if statement filters out all the grades less than 60. The secondif statement executes only if the first test is false; when the second if
statement executes, the value of grade is 60 or greater. The second if
statement filters out all the grades 60 through 69 inclusive. The third if
statement executes only if the first two tests are false; when the third if
statement executes, the value of grade is 70 or greater
7/30/2019 Computer Science 1302
39/111
3939
FLAGS
A flag is a boolean variable that signals when some condition existsin a program. When the flag variable has the valuefalse it meansthe condition does not exist. When the flag variable is true it meansthe condition exists.
7/30/2019 Computer Science 1302
40/111
40
*** See the programAssignGradesUsesFlagVar.java
In the programAssignGradesUsesFlagVar.java, the variable
named validGrade is a flag variable that is used to signal that
a valid grade was entered.
7/30/2019 Computer Science 1302
41/111
4141
NESTED ifSTATEMENTS
There are no restrictions on what statements can be inside theconditionally executed block(s) ofifor if/else statements. Aconditionally executed block may contain an ifor if/elsestatement.
We say that an ifor an if/else statement is nested, if it is inside aconditionally executed block of another ifor if/else statement.
An else is associated with the most recent unmatched ifin thesame block. Remember, indentation does not matter to the
compiler.
7/30/2019 Computer Science 1302
42/111
42
*** See the program CalculateGrossPayWInputValid.java
7/30/2019 Computer Science 1302
43/111
4343
LOGICAL OPERATORS
We can combine two boolean expressions into a single expression
using the logical operators && (AND) or | | (OR).
7/30/2019 Computer Science 1302
44/111
4444
LOGICAL OPERATORS
The && Operator
The && operator, the logical AND operator, is a binary operatorthat takes two boolean expressions as its operands and combines
them into a boolean expression that has the value true, only
when both of the operands have the value true.
If either or both of the operands of the && operator are false, theexpression has the value false.
The && operator has lower precedence than the arithmetic andrelational operators, but higher precedence than the assignment
operators.
*** See Appendix C of the text on the CD-ROM that came with
the text
7/30/2019 Computer Science 1302
45/111
4545
LOGICAL OPERATORS
The && Operator
if(gameOver == true && player1Score > player2Score){
System.out.println("Player 1 is the winner!");}
The conditional expression, (gameOver == true && player1Score >player2Score), is true and Player 1 is the winner! is displayed, only
ifbothgameOveris equal to true andplayer1Score is greater than
layer2Score.
7/30/2019 Computer Science 1302
46/111
4646
LOGICAL OPERATORS
The && Operator
if(gameOver == true && player1Score > player2Score){
System.out.println("Player 1 is the winner!");}
The statement above is equivalent to:
if(gameOver && player1Score > player2Score){
System.out.println("Player 1 is the winner!");}
7/30/2019 Computer Science 1302
47/111
4747
LOGICAL OPERATORS
The && Operator
If left operand of a logical && operator is false, the expression
on the right will not even be evaluated. This is called short-circuit evaluation. It is a waste of processor time to evaluate theexpression that is the right operand.
if(gameOver == true && player1Score > player2Score){
System.out.println("Player 1 is the winner!");}
7/30/2019 Computer Science 1302
48/111
4848
LOGICAL OPERATORS
The && Operator
The statement below specifies that the value in the variablez isincreased by 1 and the value in the variable w is decreased by 2,when bothch1 contains the Unicode value of the letter A andy hassome value greater than 3.0.
if (ch1 == A && y > 3.0){
z += 1;
w = 2;}
7/30/2019 Computer Science 1302
49/111
4949
LOGICAL OPERATORS
The && Operator
if (ch1 == A && y > 3.0){
z += 1;
w = 2;}
The statement above is equivalent to:
if (ch1 == A){
if (y > 3.0){
z += 1;
w = 2;}
}
7/30/2019 Computer Science 1302
50/111
5050
LOGICAL OPERATORS
The && Operator
The && operator is useful for checking that a value is inside a
numeric range.
7/30/2019 Computer Science 1302
51/111
5151
LOGICAL OPERATORS
The && Operator
int month = 0;
System.out.print("Enter the number of the month [JAN = 1, FEB = 2, etc.]: ");month = keyboard.nextInt( );
if(month >= 1 && month
7/30/2019 Computer Science 1302
52/111
5252
LOGICAL OPERATORS
The && Operator
if(month >= 1 && month
7/30/2019 Computer Science 1302
53/111
5353
LOGICAL OPERATORS
The && Operator
To test whether a value is inside a range, determine if it is both> or >= to the lower end of the range AND (&&) < or or >= and < or = 1 && month
7/30/2019 Computer Science 1302
54/111
5454
LOGICAL OPERATORS
The && Operator
We could check if we had an uppercase letter in the charvariablech1 by writing:
if(ch1 >= 'A' && ch1
7/30/2019 Computer Science 1302
55/111
5555
LOGICAL OPERATORS
The || Operator
The || operator, the logical OR operator, is a binary operator thattakes two boolean expressions as its operands and combines
them into a boolean expression that has the value true, when
either or both of its operands are true. In other words, the ||
operation is true ifat least one of its operands is true.
The || operation is false only when both of the operands of the ||are false.
The || operator has lower precedence than the && operator, buthigher precedence than the assignment operators.
*** See Appendix C of the text on the CD-ROM that came
with the text
7/30/2019 Computer Science 1302
56/111
5656
LOGICAL OPERATORS
The || Operator
if (weight < 0 || height < 0){
goodData = false;}
The conditional expression, (weight < 0 || height < 0), is true and
goodData is assigned the value false, if at least one of weight < 0OR height < 0 are true.
7/30/2019 Computer Science 1302
57/111
5757
LOGICAL OPERATORS
The || Operator
If the expression on the left side of the || operator is true, the
expression on the right will not be evaluated. Again, this is calledshort-circuit evaluation.
if (weight < 0 || height < 0){
goodData = false;}
7/30/2019 Computer Science 1302
58/111
5858
LOGICAL OPERATORS
The || Operator
The || operator is useful for checking whether a value is outside
a numeric range.
7/30/2019 Computer Science 1302
59/111
5959
LOGICAL OPERATORS
The || Operator
In the segment below, the conditional expression (month < 1 ||
month > 12) is true and theprintln statement is executed if
month is less than 1 ORmonth is greater than 12:
if (month < 1 || month > 12){
System.out.println("\nError: The month should be a value from 1 through 12.");}
7/30/2019 Computer Science 1302
60/111
6060
LOGICAL OPERATORS
The || Operator
To test whether a value is outside a range, determine if it is eitherless than the lower end of the range OR (||) greater than the upperend of the range.
if (month < 1 || month > 12){
System.out.println("\nError: The month should be a value from 1 through 12.");}
7/30/2019 Computer Science 1302
61/111
7/30/2019 Computer Science 1302
62/111
6262
LOGICAL OPERATORS
The ! Operator
The ! operator, the logical complement operator or the notoperator, is a unary operator that complements the logical value
of the boolean expression that is its operand.
The ! operator reverses its operands truth or falsehood.
If
expressionhas the value true, !(
expression) is false.
Ifexpression has the value false, !(expression) is true.
7/30/2019 Computer Science 1302
63/111
6363
LOGICAL OPERATORS
The ! Operator
double radius = 1, area = 1;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the radius of the circle: ");radius = keyboard.nextDouble( );
if(!(radius
7/30/2019 Computer Science 1302
64/111
6464
LOGICAL OPERATORS
The ! Operator
Equivalently, the statement below could begin if(radius > 0)
if(!(radius
7/30/2019 Computer Science 1302
65/111
6565
LOGICAL OPERATORS
The ! Operator
The ! operator has relatively high precedence. It has higherprecedence than the arithmetic, relational, and other logicaloperators.
*** See Appendix C of the text on the CD-ROM that came with
the text
7/30/2019 Computer Science 1302
66/111
6666
LOGICAL OPERATORS
The ! Operator
(!radius
7/30/2019 Computer Science 1302
67/111
6767
LOGICAL OPERATORS
The ! Operator
We could write:
if(!error){
// Put statements here that you want executed when error is false// When error is true these statements are skipped.
.
.
.}
(error == false) is equivalent to the conditional expression in the
statement above.
7/30/2019 Computer Science 1302
68/111
68
Suppose we had already created the pseudocode for a program to
get a numeric grade earned on assignment from the user and assign
the letter grade corresponding to the numeric grade using the scalebelow, and then we learned that valid grades are in the range 0
through 100.
grades 59 letter grade of F
60 grades 69 letter grade of D70 grades 79 letter grade of C
80 grades 89 letter grade of B
90 grades letter grade of A
7/30/2019 Computer Science 1302
69/111
69
Lets modify the pseudocode and program so that letter grades are
only assigned for valid numeric grades and an appropriate error
message is displayed if an invalid numeric grade is entered.
Pseudocode for the programAssignGrades.java
Get the number of points earned on the assignment and store this in grade
If grade < 60Set letterGrade to F
Else if grade < 70Set letterGrade to D
Else if grade < 80Set letterGrade to C
Else if grade < 90
Set letterGrade to BElse
Set letterGrade to A
Display the letter Grade
7/30/2019 Computer Science 1302
70/111
7/30/2019 Computer Science 1302
71/111
71
*** See the programAssignGradesUsesLogOper.java
7/30/2019 Computer Science 1302
72/111
7272
COMPARING String OBJECTS
You cannot use the relational operators >, =, and
7/30/2019 Computer Science 1302
73/111
7373
COMPARING String OBJECTS
For example, when the segment below is executed, the conditionalexpression, (day == enteredDay), always evaluates tofalse andThe current day is not Monday. is always displayed in the dialogbox, because the objects referenced by day and enteredDay are indifferent memory locations (i.e. they have different memory
addresses).
String day = "Monday";String enteredDay;
enteredDay = JOptionPane.showInputDialog("Enter the current day of the week.");
if(day == enteredDay){
JOptionPane.showMessageDialog(null, "The current day is Monday.");}else{
JOptionPane.showMessageDialog(null, "The current day is not Monday.");
}
7/30/2019 Computer Science 1302
74/111
7474
COMPARING String OBJECTS
String day = "Monday";String enteredDay;
enteredDay = JOptionPane.showInputDialog("Enter the current day of the week.");
if(day == enteredDay){
JOptionPane.showMessageDialog(null, "The current day is Monday.");
}else{
JOptionPane.showMessageDialog(null, "The current day is not Monday.");}
7/30/2019 Computer Science 1302
75/111
7575
COMPARING String OBJECTS
The equals( ) Method of a String Object
To compare the contents of two String objects to see if they containthe same string, use the String objects equals( ) method.
The general form of a call to the method is:
StringReference.equals(OtherString)
StringReference is a variable that references a String object
and OtherString is either a variable that references a String object or
a string literal.
The equals( ) method returns the value true if the two strings are
equal and the valuefalse if they are not equal.
7/30/2019 Computer Science 1302
76/111
7676
COMPARING String OBJECTS
The equals( ) Method of a String Object
The conditional expression in the segment below compares thecontents of the String objects that are referenced by day and
enteredDay. If the strings are equal, the conditional expression is
true, and The current day is Monday. is displayed. If the strings are
not equal, the conditional expression isfalse, and The current day is
not Monday. is displayed.
String day = "Monday";String enteredDay;
enteredDay = JOptionPane.showInputDialog("Enter the current day of the week.");
if(day.equals(enteredDay)){
JOptionPane.showMessageDialog(null, "The current day is Monday.");}else{
JOptionPane.showMessageDialog(null, "The current day is not Monday.");
}
7/30/2019 Computer Science 1302
77/111
7777
COMPARING String OBJECTS
The equals( ) Method of a String Object
String day = "Monday";String enteredDay;
enteredDay = JOptionPane.showInputDialog("Enter the current day of the week.");
if(day.equals(enteredDay)){
JOptionPane.showMessageDialog(null, "The current day is Monday.");
}else{
JOptionPane.showMessageDialog(null, "The current day is not Monday.");}
7/30/2019 Computer Science 1302
78/111
7/30/2019 Computer Science 1302
79/111
7979
COMPARING String OBJECTS
ThecompareTo( ) Method of a String Object
Objects of the String class also have a method called compareTo( ). Wecan use this method to determine if one string is greater than, equal to, or
less than another string.
The general form of a call to the method is:
StringReference.compareTo(OtherString)
StringReference is a variable that references a String object and
OtherString is either a variable that references a String object or a string
literal.
7/30/2019 Computer Science 1302
80/111
8080
COMPARING String OBJECTS
ThecompareTo( ) Method of a String Object
StringReference.compareTo(OtherString)
The compareTo( ) method returns an integer value. The value returned
indicates what relationship exists between the two strings:
When the string referenced by StringReference islexicographically less than OtherString the compareTo( ) method
returns a negative value.
When the string referenced by StringReference is
lexicographically equivalent to OtherString the compareTo( )
method returns zero. When the string referenced by StringReference is
lexicographically greater than OtherString the compareTo( )
method returns a positive value.
7/30/2019 Computer Science 1302
81/111
8181
COMPARING String OBJECTS
ThecompareTo( ) Method of a String Object
StringReference.compareTo(OtherString)
The compareTo( )method compares the two strings character bycharacter (comparing the Unicode values of each character),
when the same Unicode is found, compareTo( ) moves on to the
next character. When compareTo( ) finds two characters with different
Unicodes in the same relative position, it stops the comparison.
If the Unicode code of the differing character of
StringReference is less than the code of the character in
OtherString, compareTo( ) returns a negative value.
If the Unicode code of the differing character of
StringReference is greater than the code of the character in
OtherString, compareTo( ) returns a positive value.
7/30/2019 Computer Science 1302
82/111
7/30/2019 Computer Science 1302
83/111
8383
COMPARING String OBJECTS
ThecompareTo( ) Method of a String Object
What is the value assigned to twhen the following statements areexecuted? ___________
String string1 = "Mars";String string2 = "Mercury";
int t = string1.compareTo(string2);
7/30/2019 Computer Science 1302
84/111
8484
COMPARING String OBJECTS
ThecompareTo( ) Method of a String Object
What is the value assigned to v when the following statements areexecuted? ____________
String string3 = "catapillar";String string4 = "cat";
int v = string3.compareTo(string4);
7/30/2019 Computer Science 1302
85/111
8585
COMPARING String OBJECTS
ThecompareTo( ) Method of a String Object
What is the value assigned to w when the following statements areexecuted? _____________
String string5 = "water";String string6 = "Water";
int w = string5.compareTo(string6);
7/30/2019 Computer Science 1302
86/111
8686
COMPARING String OBJECTS
The equals( ) and compareTo( ) methods perform case sensitivecomparisons.
Objects of the String class also have methodsequalsIgnoreCase( )and compareToIgnoreCase( ).
The equalsIgnoreCase( ) method works like the equals( )method, but the case of the characters in the strings are ignored
in the equalsIgnoreCase( ) version.
The compareToIgnoreCase( ) method works like thecompareTo( ) method, but the case of the characters in the
strings are ignored in the compareToIgnoreCase( ) version.
7/30/2019 Computer Science 1302
87/111
8787
FORMATTING FLOATING-POINT VALUES
WITH THEDecimalFormat Class
We can use theDecimalFormatclass to control the way floating-point numbers are displayed.
TheDecimalFormatclass is part of the Java API, but it is notavailable to your program unless you include the followingimport statement before the class definitions in your source file.
import java.text.DecimalFormat;
7/30/2019 Computer Science 1302
88/111
8888
FORMATTING FLOATING-POINT VALUES
WITH THEDecimalFormat Class
To use theDecimalFormatclass we create an object or instance ofthis class in memory using the new operator.
DecimalFormat format = new DecimalFormat("000.#");
7/30/2019 Computer Science 1302
89/111
8989
FORMATTING FLOATING-POINT VALUES
WITH THEDecimalFormat Class
DecimalFormat format = new DecimalFormat("000.#");
On the left side of the assignment operator, we are declaring areference variable namedformat.
Variable name
7/30/2019 Computer Science 1302
90/111
FORMATTING FLOATING POINT VALUES
7/30/2019 Computer Science 1302
91/111
9191
FORMATTING FLOATING-POINT VALUES
WITH THEDecimalFormat Class
DecimalFormat format = new DecimalFormat("000.#");
On the right side of the assignment operator, we use the newoperator to instantiate an object of theDecimalFormatclass.
When an object is created, a special method called a constructor is
executed.
Instatiates an object inmemory
7/30/2019 Computer Science 1302
92/111
FORMATTING FLOATING POINT VALUES
7/30/2019 Computer Science 1302
93/111
9393
FORMATTING FLOATING-POINT VALUES
WITH THEDecimalFormat Class
DecimalFormat format = new DecimalFormat("000.#");
The new operator returns the address of the object that is created inmemory and we are assigning this to the reference variableformat.
The address of the object
is assigned to thereference variable.
FORMATTING FLOATING POINT VALUES
7/30/2019 Computer Science 1302
94/111
9494
FORMATTING FLOATING-POINT VALUES
WITH THEDecimalFormat Class
DecimalFormat format = new DecimalFormat("000.#");
The formatting pattern shows how values formatted using thisobject will be displayed.
The characters before the decimal point specify the minimum
number of digits that should be displayed before the decimalpoint.
If there are more actual digits before the decimal point they willbe displayed regardless of the pattern.
This is theformatting
pattern
FORMATTING FLOATING POINT VALUES
7/30/2019 Computer Science 1302
95/111
9595
FORMATTING FLOATING-POINT VALUES
WITH THEDecimalFormat Class
DecimalFormat format = new DecimalFormat("000.#");
The characters after the decimal point show the maximumnumber of digits to be displayed after the decimal point.
If there are more digits after the decimal point than are specifiedthe value will be rounded to the specified number of digits.
This is theformatting
pattern
FORMATTING FLOATING POINT VALUES
7/30/2019 Computer Science 1302
96/111
9696
FORMATTING FLOATING-POINT VALUES
WITH THEDecimalFormat Class
DecimalFormat format = new DecimalFormat("000.#");
The 0 character represents a required digit if there is no digitin the position a zero is displayed
The # character represents an optional digit if there is no digitin the position or the digit is a zero, no digit is displayed
This is theformatting
pattern
FORMATTING FLOATING POINT VALUES
7/30/2019 Computer Science 1302
97/111
9797
FORMATTING FLOATING-POINT VALUES
WITH THEDecimalFormat Class
DecimalFormat format = new DecimalFormat("000.#");
The pattern, 000.#, means display at least three digits to theleft of the decimal point and a maximum of one digit to the right
of the decimal point. Leading zeroes will be included if necessary to get the three
digits to the left of the decimal point.
If there is a nonzero fractional portion it will be rounded to onedigit to the right of the decimal point. If there is no fractional
portion, none will be displayed.
For example, if the value 1234.56 was formatted according to thepattern above. The value would become 1234.6.
FORMATTING FLOATING POINT VALUES
7/30/2019 Computer Science 1302
98/111
9898
FORMATTING FLOATING-POINT VALUES
WITH THEDecimalFormat Class
Once you have created aDecimalFormatobject, you can call itsformat( ) method to format the value that is passed as an
argument to the method.
Theformat( ) method creates a String object containing thecharacters corresponding to the formatted number and
returns the address of the String object.
DecimalFormat format1 = new DecimalFormat("000.#");
double f = 12.0;
String formattedNumber;
formattedNumber = format1.format(f);System.out.println(formattedNumber); // Displays 012
7/30/2019 Computer Science 1302
99/111
99
*** See the programDemoDecForm.java which is available
on webct
THE switch STATEMENT
7/30/2019 Computer Science 1302
100/111
100100
THEswitch STATEMENT
The switch statement is a decision structure that allows you to specify abranch to a segment of code based upon matching the value of the testexpression with a constant expression following the keyword case at thebeginning of the segment.
switch (test expression)
{case constant expression:
optional statement(s)
case constant expression:optional statement(s)
case constant expression:optional statement(s)
default:statement(s) // Default case is optional
}
THE switch STATEMENT
7/30/2019 Computer Science 1302
101/111
101101
THEswitch STATEMENT
The switch statement begins with the keyword switch, followedby a parenthesizedtest expression. This test expression mustevaluate to a value of type int, short, byte, or char.
switch (test expression){
case constant expression:optional statement(s)
case constant expression:optional statement(s)
case constant expression:optional statement(s)
default:statement(s) // Default case is optional
}
THE switch STATEMENT
7/30/2019 Computer Science 1302
102/111
102102
THEswitch STATEMENT
A block of case statements follows the test expression. Each ofthe case statements begins with the keyword case and is
followed by a constant expression and a colon.
switch (test expression){
case constant expression:
optional statement(s)
case constant expression:optional statement(s)
case constant expression:optional statement(s)
default:statement(s) // Default case is optional
}
A colon is at the
end of the case
label.
THE switch STATEMENT
7/30/2019 Computer Science 1302
103/111
103103
THEswitch STATEMENT
The constant expression must have a value of type int, short,byte, or char.
switch (test expression){
case constant expression:optional statement(s)
case constant expression:optional statement(s)
case constant expression:
optional statement(s)
default:statement(s) // Default case is optional
}
THE switch STATEMENT
7/30/2019 Computer Science 1302
104/111
104104
THEswitch STATEMENT
Any number of Java programming statements may appear afterthis case label.
switch (test expression){
case constant expression:optional statement(s)
case constant expression:optional statement(s)
case constant expression:optional statement(s)
default:statement(s) // Default case is optional
}
THE switch STATEMENT
7/30/2019 Computer Science 1302
105/111
105105
THEswitch STATEMENT
The parenthesized test expression is evaluated, the value of thisexpression is compared with the constant expressions in the
cases, if a matching expression is found, execution branches to
the statement(s) following the label in the matching case.
switch (test expression)
{case constant expression:
optional statement(s)
case constant expression:optional statement(s)
case constant expression:optional statement(s)
default:statement(s) // Default case is optional
}
THE switch STATEMENT
7/30/2019 Computer Science 1302
106/111
106106
THEswitch STATEMENT
Once the running program has branched to a particular case, thestatements for that case and all subsequent cases will be executedunless a breakstatement is used breakout of the switchstatement.
switch (test expression)
{case constant expression:
optional statement(s)
case constant expression:optional statement(s)
case constant expression:optional statement(s)
default:statement(s) // Default case is optional
}
THE switch STATEMENT
7/30/2019 Computer Science 1302
107/111
107107
THEswitch STATEMENT
The breakstatement causes a break/exit from the block of theswitch statement to the first statement following the switch block.
switch (test expression){
case constant expression:
optional statement(s)
case constant expression:optional statement(s)
case constant expression:
optional statement(s)
default:statement(s) // Default case is optional
}
The switch block isbetween the braces.
7/30/2019 Computer Science 1302
108/111
7/30/2019 Computer Science 1302
109/111
109109
*** See the program SwitchDemo.java from the text
This same program could have been written using an if/elseifinstead
of the switch statement.
Try taking out the breaks and see what happens!!!
THE switch STATEMENT
7/30/2019 Computer Science 1302
110/111
110110
THEswitch STATEMENT
Not every if/else if statement can be converted to a switch statement.Decisions based on range of values are more easily specified using anif/elseif. It is difficult, if not impossible, to enumerate all the values in alarge range.
What ifx is some integer type?What ifx is some floating-point type?
if (x < 5){
y = x;}else if (x
7/30/2019 Computer Science 1302
111/111
*** See the program TicketPurchase.java which is availableon webct