S3
S3
JAVA PROGRAMMING
Chapter 3: SELECTIONS 1
The Boolean Type and Operators
• Often in a program you need to compare 2 values, the
result of the comparison is a Boolean value: true or false.
boolean b = (1 > 2);
• Java provides 6 comparison operators (also known as
relational operators) that can be used to compare 2 values.
2
Problem: A Simple Math Learning Tool
• This example creates a program to let a first grader practice
additions.
• The program
1. randomly generates two single-digit integers number1 and
number2
2. and displays a question such as “What is 7 + 9?” to the student.
After the student types the answer,
3. the program displays a message to indicate whether the answer
is true or false.
3
Problem: A Simple Math Learning Tool
Run
4
One-way if Statements
5
One-way if Statements
6
One-way if Statements
Recommended
7
Problem: Guessing Birthday
• You can find out the date of the month when your friend
was born by asking 5 questions.
• Each question asks whether the day is in one of the five
sets of numbers.
9
Problem: Guessing Birthday
10
Problem: Guessing Birthday
11
Problem: Guessing Birthday
12
Problem: Guessing Birthday
13
Problem: Guessing Birthday
Run
14
Mathematics Basis for the Game
• If a day’s binary number has a digit 1 in bk the number
should appear in Setk
• 19 is 10011 in binary. 7 is 111 in binary. 23 is 10111 in
binary 10000
10000 00110
0 1000
0 1
10 10 100
01
+ 1 + 1 + 1
10011 00111 11101
011
19 7 23
15
The Two-way if Statement
One-way if
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
16
if...else Example
if (radius >= 0) {
area = radius * radius * PI;
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
else {
System.out.println("Negative input");
}
17
Nested if and Multi-Way if-else Statements
• A multi-Way if-else, assigns a letter grade to the variable
grade according to the score, with multiple alternatives
18
Trace if-else statement
Suppose score is 70.0 The condition is false
19
Trace if-else statement
Suppose score is 70.0 The condition is false
20
Trace if-else statement
Suppose score is 70.0 The condition is true
21
Trace if-else statement
Suppose score is 70.0 grade is C
22
Trace if-else statement
Suppose score is 70.0 Exit the if statement
23
Common Errors in Selection Statements
Common Error 1: Forgetting Necessary Braces
24
Common Errors in Selection Statements
Common Error 2: Wrong Semicolon at the if Line
25
Common Errors in Selection Statements
Common Error 3: Using the = operator instead of the ==
26
Common Errors in Selection Statements
Common Error 4: Dangling else Ambiguity
• Which if clause is matched by the else clause?
• Nothing is printed
28
Common Errors in Selection Statements
Common Error 4: Dangling else Ambiguity
• To force the else clause to match the first if clause, you
must add a pair of braces:
29
TIP
• Often new programmers write the code that assigns a test
condition to a Boolean variable
30
Note: Redundant Testing of Boolean Values
• To test whether a Boolean variable is true or false in a test
condition, it is redundant to use the equality comparison
operator
31
Generating Random Numbers
• The previous programs generate random numbers using
System.currentTimeMillis().
32
An Improved Math Learning Tool for first grade child
• Suppose you want to develop a program for a first-grader
to practice subtraction. The program can work as follows:
1. Generate 2 random single-digit integers into number1 and
number2.
33
Problem:
An Improved Math Learning Tool for first grade child
34
Problem:
An Improved Math Learning Tool for first grade child
Run
35
Problem: Body Mass Index
• Body Mass Index (BMI) is a measure of health based on
height and weight.
36
Problem: Body Mass Index
37
Problem: Body Mass Index
Run
38
Problem: Computing Taxes
• The US federal personal income tax is calculated based on filing status
and taxable income.
• There are 4 filing statuses: single filers, married filing jointly or
qualified widow(er), married filing separately, and head of household.
• The tax rates vary every year. Table 3.2 shows the rates for 2009. If
you are, say, single with a taxable income of $10,000, the first $8,350
is taxed at 10% and the other $1,650 is taxed at 15%, so, your total
tax is $1,082.50.
39
Problem: Computing Taxes
• You are to write a program to compute personal income tax.
• Your program should prompt the user to enter the filing status and
taxable income and compute the tax.
• Enter 0 for single filers, 1 for married filing jointly or qualified
widow(er), 2 for married filing separately, and 3 for head of
household.
40
Problem: Computing Taxes
41
Problem: Computing Taxes
42
Problem: Computing Taxes
Run 43
Logical Operators
• The logical operators !, &&, ||, and ^ can be used to create
a compound Boolean expression
44
Logical Operators
45
Logical Operators
46
Note 1
• As shown in the preceding chapter, a char value can be cast
into an int value, and vice versa.
• A boolean value, however, cannot be cast into a value of
another type, nor can a value of another type be cast into a
boolean value.
47
Note 2
• De Morgan’s law, named after Indian-born British
mathematician and logician Augustus De Morgan (1806–
1871), can be used to simplify Boolean expressions. The
law states:
!(condition1 && condition2) = !condition1 || !condition2
48
Case Study: Determining Leap Year
• A year is a leap year if it is divisible by 4 but not by 100, or if
it is divisible by 400.
Run 49
Case Study: Lottery
• Suppose you want to develop a program to play lottery. The
program randomly generates a lottery of a two-digit
number (00..99), prompts the user to enter a two-digit
number, and determines whether the user wins according
to the following rules:
1. If the user input matches the lottery number in the exact
order, the award is $10,000.
2. If all the digits in the user input match all the digits in the
lottery number, the award is $3,000.
3. If one digit in the user input matches a digit in the lottery
number, the award is $1,000 50
Case Study: Lottery
51
Case Study: Lottery
Run
52
Switch statement
• A switch statement executes statements based on the value
of a variable or an expression.
• You can write the following switch statement to replace the
nested if statement in Listing 3.6
53
Switch statement
54
Switch statement
• Full syntax for the switch statement The switch-expression must
yield a value of char,
byte, short, int, or
String (new in JDK 7) type
and must always be
enclosed in parentheses.
55
Switch statement
• Full syntax for the switch statement
The keyword break is
optional. The break
statement immediately
ends the switch
statement
Note: The case statements are executed in sequential order, but the
order of the cases (including the default case) does not matter.
However, it is good programming style to follow the logical sequence of
the cases and place the default case at the end. 56
Caution
• When the value in a case statement matches the value of
the switch-expression, the statements starting from this
case are executed until either a break statement or the end
of the switch statement is reached. This is referred to as
fall-through behaviour.
• The following code displays the character a three times if
ch is a.
57
Trace switch statement
Suppose ch is 'a':
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
58
Trace switch statement
ch is 'a':
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
59
Trace switch statement
Execute this line
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
60
Trace switch statement
Execute this line
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
61
Trace switch statement
Execute this line
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
62
Trace switch statement
Execute next statement
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
Next statement;
63
Trace switch statement
Suppose ch is 'a':
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
64
Trace switch statement
ch is 'a':
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
65
Trace switch statement
Execute this line
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
66
Trace switch statement
Execute this line
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
67
Trace switch statement
Execute next statement
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
Next statement;
68
Problem: Chinese Zodiac sign
• The Chinese Zodiac is based on a twelve-year cycle, with
each year represented by an animal— monkey, rooster,
dog, pig, rat, ox, tiger, rabbit, dragon, snake, horse, or
sheep—in this cycle, as shown in the figure below
69
Problem: Chinese Zodiac sign
Run 70
Conditional Expressions
Is equivalent to
• Other examples:
max = (num1 > num2) ? num1 : num2;
72
Formatting Console Output
• You can use the System.out.printf method to display
formatted output on the console.
• The syntax to invoke this method is
System.out.printf (format, item1, item2, ..., itemk) where
format is a string that may consist of
1. substrings
2. format specifiers.
• A format specifier specifies how an item should be
displayed.
• An item may be a numeric value, a character, a boolean
value, or a string. 73
Format specifiers
• A complete format specifier consists of a percent sign (%)
followed by
– field width,
– a decimal point,
– precision
– conversion code.
= 16.404674
74
Format specifiers
• Table 3.8 lists some frequently used simple format
specifiers.
75
Formatting Console Output, cont.
• Another example:
77
Formatting Console Output
• Here is an other example:
80
Operator Precedence and Associativity
2. right associative
82
(GUI) Confirmation Dialogs
• You can use a confirmation dialog to obtain a confirmation
from the user.
83
(GUI) Confirmation Dialogs
• When a button is clicked, the method returns an option
value. The value is
– JOptionPane.YES_OPTION which is 0 for the Yes button,
84
Rewrite problem: Guessing Birth Date
• You may rewrite the guess-birthday program in Listing 3.3
using confirmation dialog boxes
85
Rewrite problem: Guessing Birth Date
86
Rewrite problem: Guessing Birth Date
87
Rewrite problem: Guessing Birth Date
Run 88
Homework
• Study all materials in chapter 3 from the textbook
• Exercises:
3.1, 3.3, 3.4, 3.9, 3.16, 3.21, 3.22, 3.25, 3.27, 3.28,
3.29, 3.32, 3.34, 3.35
from chapter 3
89