Professional Documents
Culture Documents
CMPS161 Class Notes Chap 03
CMPS161 Class Notes Chap 03
CMPS161 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
Examples
System.out.println(1 < 2); // Displays true
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 true, the statements in
the block are executed
if i > 0 { if (i > 0) {
System.out.println("i is positive"); System.out.println("i is positive");
} }
(a) Wrong (b) Correct
if (i > 0) { if (i > 0)
System.out.println("i is positive"); Equivalent System.out.println("i is positive");
}
(a) (b)
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
FIGURE 3.2 An if-else statement 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;
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
else {
System.out.println("Negative input"); // braces may be omitted
}
Note: If radius >= 0 is true, area is computed and displayed; if it is false, the message
“Negative input” is printed.
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.”);
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)
(a) (b)
FIGURE 3.3 A preferred format for multiple alternatives is shown in (b) using a multi-
way if-else statement.
FIGURE 3.4 You can use a multi-way if-else statement to assign a grade.
(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:
o The code can be simplified by assigning the test value directly to the variable, as
shown in (b). This is not an error, but it should be better written as shown in (b).
if (inState) {
tuition = 5000;
}
else {
tuition = 15000;
}
System.out.println("The tuition is " + tuition);
o The new code removes the duplication and makes the code easy to maintain,
because you only need to change in one place if the print statement is modified.
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
import java.util.Scanner;
public class ComputeAndInterpretBMI {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Compute BMI
double weightInKilograms = weight * KILOGRAMS_PER_POUND;
double heightInMeters = height * METERS_PER_INCH;
double bmi = weightInKilograms /
(heightInMeters * heightInMeters);
// Display result
System.out.println("BMI is " + bmi);
if (bmi < 18.5)
System.out.println("Underweight");
else if (bmi < 25)
System.out.println("Normal");
else if (bmi < 30)
System.out.println("Overweight");
else
System.out.println("Obese");
}
} Enter weight in pounds: 146
Enter height in inches: 70
BMI is 20.948603801493316
Normal
import java.util.Scanner;
// Compute tax
double tax = 0;
|| or logical disjunction
Examples
&& (and) (1 < x) && (x < 100)
|| (or) (lightsOn) || (isDayTime)
! (not) !(isStopped)
// Receive an input
System.out.print("Enter an integer: ");
int number = input.nextInt();
if (number % 2 == 0 || number % 3 == 0)
System.out.println(number + " is divisible by 2 or 3.");
if (number % 2 == 0 ^ number % 3 == 0)
System.out.println(number +
" divisible by 2 or 3, but not both.");
}
}
Enter an integer: 4
4 is divisible by 2 or 3.
4 divisible by 2 or 3, but not both.
Enter an integer: 18
18 is divisible by 2 and 3.
18 is divisible by 2 or 3.
import java.util.Scanner;
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.
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. Once a case is matched,
the statements starting from the matched case are executed until a break statement or
the end of the switch statement is reached. This is referred to as fall-through behavior.
For example, the following code displays Weekdays for day of 1 to 5 and Weekends
for day 0 and 6.
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
import java.util.Scanner;
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.
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