C Mps 161 Class Notes Chap 03
C Mps 161 Class Notes Chap 03
Selections
3.1 Introduction
• Java provides selections that let you choose actions with two or more alternative
courses.
• Selection statements use conditions. Conditions are Boolean expressions.
• Java has several types of selection statements:
o if Statements, if … else statements, nested if statements
o switch Statements
o Conditional Expressions
• Often in a program you need to compare two values, such as whether i is greater than
j. Java provides six comparison operators (also known as relational operators) that
can be used to compare two values. The result of the comparison is a Boolean value:
true or false.
• Examples
System.out.println(1 < 2); // Displays true
• This example creates a program to let a first grader practice additions. The program
randomly generates two single-digit integers number1 and number2 and displays a
question such as “What is 7 + 9?” to the student. After the student types the answer,
the program displays a message to indicate whether the answer is true or false.
• LISTINT 3.1 AdditionQuiz.java
import java.util.Scanner;
// Create a Scanner
Scanner input = new Scanner(System.in);
System.out.print(
"What is " + number1 + " + " + number2 + "? ");
System.out.println(
number1 + " + " + number2 + " = " + answer + " is " +
(number1 + number2 == answer));
}
}
What is 1 + 7? 8
1 + 7 = 8 is true
What is 4 + 8? 9
4 + 8 = 9 is false
Example
if (radius >= 0) {
area = radius * radius * PI;
System.out.println("The area for the circle of radius " +
radius + " is " + area);
} // if the Boolean expression evaluates to T, the statements in the
block are executed as shown in figure (B)
false false
Boolean (radius >= 0)
Expression
true true
(A) (B)
Outer parentheses required Braces can be omitted if the block contains a single
statement
if ((i > 0) && (i < 10)) { Equivalent if ((i > 0) && (i < 10))
System.out.println("i is an " + System.out.println("i is an " +
+ "integer between 0 and 10"); + "integer between 0 and 10");
}
(a)
(b)
• Write a program that prompts the user to enter an integer. If the number is a multiple
of 5, print HiFive. If the number is divisible by 2, print HiEven.
• LISTING 3.2 SimpleIfDemo.java
import java.util.Scanner;
if (number % 5 == 0)
System.out.println("HiFive");
if (number % 2 == 0)
System.out.println("HiEven");
}
}
Enter an integer: 4
HiEven
Enter an integer: 30
HiFive
HiEven
1 3 5 7 2 3 6 7 4 5 6 7 8 9 10 11 16 17 18 19
9 11 13 15 10 11 14 15 12 13 14 15 12 13 14 15 20 21 22 23
17 19 21 23 18 19 22 23 20 21 22 23 24 25 26 27 24 25 26 27
25 27 29 31 26 27 30 31 28 29 30 31 28 29 30 31 28 29 30 31
Set1 Set2 Set3 Set4 Set5
19 7 23
Is your birthday in Set1?
1 3 5 7
• LISTING 3.3 GuessBirthday.java 9 11 13 15
17 19 21 23
import java.util.Scanner; 25 27 29 31
Enter 0 for No and 1 for Yes: 1
public class GuessBirthday {
Is your birthday in Set2?
public static void main(String[] args) {
2 3 6 7
String set1 = 10 11 14 15
" 1 3 5 7\n" + 18 19 22 23
" 9 11 13 15\n" + 26 27 30 31
"17 19 21 23\n" + Enter 0 for No and 1 for Yes: 1
"25 27 29 31";
Is your birthday in Set3?
String set2 = 4 5 6 7
" 2 3 6 7\n" + 12 13 14 15
20 21 22 23
"10 11 14 15\n" +
28 29 30 31
"18 19 22 23\n" + Enter 0 for No and 1 for Yes: 0
"26 27 30 31"; Ï
Is your birthday in Set4?
String set3 = 8 9 10 11
" 4 5 6 7\n" + 12 13 14 15
"12 13 14 15\n" + 24 25 26 27
"20 21 22 23\n" + 28 29 30 31
"28 29 30 31"; Enter 0 for No and 1 for Yes: 0
Ï
String set4 = Is your birthday in Set5?
" 8 9 10 11\n" + 16 17 18 19
20 21 22 23
"12 13 14 15\n" + 24 25 26 27
"24 25 26 27\n" + 28 29 30 31
"28 29 30 31"; Enter 0 for No and 1 for Yes: 1
Ï
String set5 = Your birthday is 19!
"16 17 18 19\n" +
int day = 0;
// Create a Scanner
Scanner input = new Scanner(System.in);
if (answer == 1)
day += 1;
if (answer == 1)
day += 2;
if (answer == 1)
day += 4;
if (answer == 1)
day += 8;
if (answer == 1)
day += 16;
true false
Boolean
Expression
Statement(s) for the true case Statement(s) for the false case
FIGURE 3.3 An if … else executes statements for the true case if the Boolean expression evaluations are
true; otherwise, statements for the false case are executed.
• if...else Example
if (radius >= 0) {
area = radius * radius * PI;
• Using the if … else statement, you can rewrite the following code for determining
whether a number is even or odd, as follows:
if (number % 2 == 0)
System.out.println(number + “ is even.”);
if (number % 2 != 0)
System.out.println(number + “is odd.”);
• The statement in an if or if ... else statement can be any legal Java statement,
including another if or if ... else statement. The inner if statement is said to be nested
inside the outer if statement.
• The inner if statement can contain another if statement.
• There is no limit to the depth of the nesting.
if (i > k) {
if (j > k)
System.out.println(“i and j are greater than k”);
}
else
System.out.println(“i is less than or equal to k”);
// the if (j > k) is nested inside the if (i > k)
• The code can be simplified by assigning the test value directly to the variable, as
shown in (b).
(a) (b)
Equivalent if (even)
if (even == true)
System.out.println( System.out.println(
"It is even."); "It is even.");
(a) (b)
Caution
o What’s wrong with the following?
if (even = true)
System.out.println(“It is even.”);
This statement does not have syntax errors. It assigns true to even so that even is
always true.
is equivalent to:
o Nothing is printed from the preceding statement because the compiler ignores
indentation. To force the else clause to match the first if clause, you must add a
pair of braces:
• This example creates a program to teach a first grade child how to learn subtractions.
The program randomly generates two single-digit integers number1 and number2
with number1 > number2 and displays a question such as “What is 9 – 2?” to the
student, as shown in the figure. After the student types the answer in the input dialog
box, the program displays a message dialog box to indicate whether the answer is
correct.
• LISTING 3.4 SubtractionQuiz.java
import java.util.Scanner;
What is 6 - 6? 0
You are correct!
What is 9 - 2? 5
Your answer is wrong.
9 - 2 should be 7
BMI Interpretation
// Compute BMI
double weightInKilograms = weight * KILOGRAMS_PER_POUND;
double heightInMeters = height * METERS_PER_INCH;
double bmi = weightInKilograms /
(heightInMeters * heightInMeters);
// Display result
System.out.printf("Your BMI is %5.2f\n", bmi);
if (bmi < 16)
System.out.println("You are seriously underweight");
else if (bmi < 18)
System.out.println("You are underweight");
else if (bmi < 24)
System.out.println("You are normal weight");
else if (bmi < 29)
System.out.println("You are overweight");
else if (bmi < 35)
System.out.println("You are seriously overweight");
else
System.out.println("You are gravely overweight");
}
}
• The US federal personal income tax is calculated based on the filing status and
taxable income. There are four filing statuses: single filers, married filing jointly,
married filing separately, and head of household. The tax rates for 2009 are shown
below.
import java.util.Scanner;
// Compute tax
double tax = 0;
• Examples
&& (and) (1 < x) && (x < 100)
|| (or) (lightsOn) || (isDayTime)
! (not) !(isStopped)
p !p Example
true false !(1 > 2) is true, because (1 > 2) is false.
false true !(1 > 0) is false, because (1 > 0) is true.
p1 p2 p1 && p2 Example
false false false (2 > 3) && (5 > 5) is false, because either (2 > 3)
and (5 > 5) is false.
false true false
(3 > 2) && (5 > 5) is false, because (5 > 5) is false.
true false false
true true true (3 > 2 && (5>= 5) is true, b/c (3 > 2) and (5 >= 5)
are both true.
p1 p2 p1 || p2 Example
import java.util.Scanner;
// Receive an input
System.out.print("Enter an integer: ");
int number = input.nextInt();
Enter an integer: 18
Is 18 divisible by 2 and 3? true
Is 18 divisible by 2 or 3? true
Is 18 divisible by 2 or 3, but not both? false
• This program first prompts the user to enter a year as an int value and checks if it is a
leap year.
• A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400.
import java.util.Scanner;
• Write a program that randomly generates a lottery of a two-digit number, prompts the
user to enter a two-digit number, and determines whether the user wins according to
the following rule:
o If the user input matches the lottery in exact order, the award is $10,000.
o If the user input match all the digits in the lottery, the award is $3,000.
o If one digit in the user input matches a digit in the lottery, the award is $1,000.
• One can write a switch statement to replace a nested if statement. For example,
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(0);
} // checks if status matches the values 0, 1, 2, or 3 respectively.
status is 0
Compute tax for single filers break
status is 1
Compute tax for married file jointly break
status is 2
Compute tax for married file separatly break
status is 3
Compute tax for head of household break
default
Default actions
Next Statement
FIGURE 3.5 The switch statement checks all cases and executes the statement in
matched cases
Caution
• Do not forget to use a break statement when one is needed. For example, the
following code prints character a three times if ch is ‘a’:
switch (ch) {
case ‘a’: System.out.println(ch);
case ‘b’: System.out.println(ch);
case ‘c’: System.out.println(ch);
}
is equivalent to
y = (x > 0) ? 1 : -1;
• For example:
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);
is equivalent to
System.out.println((num % 2 == 0)? num + “is even” : num + “is
odd”);
• For example:
Max = (num1 > num2)? num1 : num2;
Note
• The symbols ? and : appear together in a conditional expression. They form a
condition operator. The operator is called a ternary operator because it uses three
operands.
Where format is a string that may consist of substrings and format specifiers.
A format specifier specifies how an item should be displayed.
An item may be a numeric value, character, boolean value, or a string. Each specifier
begins with a percent sign.
displays
count is 5 45.56
• Items must match the specifiers in order, on number, and in exact type. By default, a
floating-point value is displayed with 6 digits after the decimal points.
int count = 5;
items
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);
• Example
3 + 4 * 4 > 5 * (4 + 3) - 1
a – b + c – d is equivalent to ((a – b) + c) – d
a = b += c = 5 is equivalent to a = (b += (c = 5))
• Example
Applying the operator precedence and associativity rule, the expression 3 + 4 * 4 > 5
* (4 + 3) - 1 is evaluated as follows:
3 + 4 * 4 > 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 > 5 * 7 – 1
(2) multiplication
3 + 16 > 5 * 7 – 1
(3) multiplication
3 + 16 > 35 – 1
(4) addition
19 > 35 – 1
(5) subtraction
19 > 34
(6) greater than
false