Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 3 Programming

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 47

Chapter 3: Selections

and Conditionals

1
The boolean Type and Operators
The result of the comparison is a Boolean value: true or false.

boolean b = (1 > 2);

2
Relational Operators

Java Mathematics Name Example Result


Operator Symbol (radius is 5)

< < less than radius < 0 false


<= ≤ less than or equal to radius <= 0 false
> > greater than radius > 0 true
>= ≥ greater than or equal to radius >= 0 true
== = equal to radius == 0 false
!= ≠ not equal to radius != 0 true

3
One-way if Statements
if (radius >= 0) {
area = radius * radius * PI;
if (boolean-expression) { System.out.println("The area"
statement(s); + " for the circle of radius "
}
+ radius + " is " + area);
}

4
Note

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)

5
The Two-way if Statement
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}

6
if-else Example

if (radius >= 0) {
area = radius * radius * 3.14159;

System.out.println("The area for the “


+ “circle of radius " + radius +
" is " + area);
}
else {
System.out.println("Negative input");
}

7
Multiple Alternative if Statements

if (score >= 90.0) if (score >= 90.0)


System.out.print("A"); System.out.print("A");
else else if (score >= 80.0)
if (score >= 80.0) Equivalent System.out.print("B");
System.out.print("B"); else if (score >= 70.0)
else System.out.print("C");
if (score >= 70.0) else if (score >= 60.0)
System.out.print("C"); System.out.print("D");
else else
if (score >= 60.0) System.out.print("F");
System.out.print("D"); This is better
else
System.out.print("F");

(a) (b)

8
Multi-Way if-else Statements

9
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

10
animation
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

11
animation
Trace if-else statement
Suppose score is 70.0 The condition is true

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

12
animation
Trace if-else statement
Suppose score is 70.0 grade is C

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

13
animation
Trace if-else statement
Suppose score is 70.0 Exit the if statement

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

14
Note
The else clause matches the most recent if clause
in the same block.

15
Note, cont.
Nothing is printed from the preceding statement. To
force the else clause to match the first if clause, you
must add a pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.
16
Common Errors
Adding a semicolon at the end of an if clause is a common
mistake.
if (radius >= 0);
Wrong
{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
This mistake is hard to find, because it is not a compilation error
or a runtime error, it is a logic error.
This error often occurs when you use the next-line block style.
17
TIP

if (number % 2 == 0) Equivalent
even = true; boolean even
else = number % 2 == 0;
even = false;
(a) (b)

18
CAUTION

Equivalent if (even)
if (even == true)
System.out.println( System.out.println(
"It is even."); "It is even.");
(a) (b)

19
Problem: Computing Taxes
Write a program that calculates income taxes. Use the below tax rate:

Income tax from employment Progressive rates from 0 to 35%

Up to ETB 600 0%

ETB 601- 1,650 10%

ETB 1,651 - 3,200 15%

ETB 3,201 - 5,250 20%

ETB 5,251 - 7,800 25%

ETB 7,801 - 10,900 30%

Above ETB 10,900 35%

20
Logical Operators

Operator Name Description

! not logical negation

&& and logical conjunction

|| or logical disjunction

^ exclusive or logical exclusion


21
Truth Table for Operator !

p !p Example (assume age = 24, weight = 140)

true false !(age > 18) is false, because (age > 18) is true.

false true !(weight == 150) is true, because (weight == 150) is false.

22
Truth Table for Operator &&

p1 p2 p1 && p2 Example (assume age = 24, weight = 140)

false false false (age <= 18) && (weight < 140) is false, because both

conditions are both false.

false true false  

false
true false (age > 18) && (weight > 140) is false, because (weight

> 140) is false.


true
true true  (age > 18) && (weight >= 140) is true, because both

(age > 18) and (weight >= 140) are 23


true.
Truth Table for Operator ||

p1 p2 p1 || p2 Example (assume age = 24, weihgt = 140)

false false false

false true true  (age > 34) || (weight <= 140) is true, because (age > 34)

is false, but (weight <= 140) is true.

true
true false (age > 14) || (weight >= 150) is false, because

(age > 14) is true.

true 24
true true  
Truth Table for Operator ^

p1 p2 p1 ^ p2 Example (assume age = 24, weight = 140)

false false false (age > 34) ^ (weight > 140) is true, because (age > 34) is false

and (weight > 140) is false.

false true true  (age > 34) ^ (weight >= 140) is true, because (age > 34) is false

but (weight >= 140) is true.

true
true false (age > 14) ^ (weight > 140) is true, because (age > 14) is

true and (weight > 140) is false.

false 25
true true  
The & and | Operators
If x is 1, what is x after this
expression?
(x > 1) & (x++ < 10)

If x is 1, what is x after this


expression?
(1 > x) && ( 1 > x++)

How about (1 == x) | (10 > x++)?


(1 == x) || (10 > x++)?
26
switch Statements
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(1);
}
27
switch Statement Flow Chart

28
switch Statement Rules
The switch-expression must
yield a value of char, byte,
switch (switch-expression) {
short, or int type and must
always be enclosed in case value1: statement(s)1;
parentheses. break;
case value2: statement(s)2;
The value1, ..., and valueN must break;
have the same data type as the …
value of the switch-expression.
The resulting statements in the case valueN: statement(s)N;
case statement are executed when break;
the value in the case statement default: statement(s)-for-default;
matches the value of the switch-
}
expression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x.
29
switch Statement Rules
The keyword break is optional,
switch (switch-expression) {
but it should be used at the end
of each case in order to case value1: statement(s)1;
terminate the remainder of the
switch statement. If the break break;
statement is not present, the
next case statement will be
case value2: statement(s)2;
executed. break;

case valueN: statement(s)N;
The default case, which is break;
optional, can be used to perform default: statement(s)-for-default;
actions when none of the
specified cases matches the }
switch-expression.
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.
30
Trace switch statement
Suppose day is 2:

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");
}

31
Trace switch statement
Match case 2

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");
}

32
Trace switch statement
Fall through case 3

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");
}

33
Trace switch statement
Fall through case 4

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");
}

34
Trace switch statement
Fall through case 5

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");
}

35
Trace switch statement
Encounter break

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");
}

36
Trace switch statement
Exit the statement

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");
}

37
Problem: Chinese Zodiac
Write a program that prompts the user to enter a year and displays the
animal for the year.

38
Conditional Expressions
if (x > 0)
y=1
else
y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
(boolean-expression) ? expression1 : expression2
Ternary operator
Binary operator
Unary operator
39
Conditional Operator

if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);

System.out.println(
(num % 2 == 0)? num + “is even” :
num + “is odd”);

40
Conditional Operator, cont.

boolean-expression ? exp1 : exp2

41
Operator Precedence
 ()
 var++, var--
 +, - (Unary plus and minus), ++var,--var
 (type) Casting
 ! (Not)
 *, /, % (Multiplication, division, and remainder)
 +, - (Binary addition and subtraction)
 <, <=, >, >= (Relational operators)
 ==, !=; (Equality)
 ^ (Exclusive OR)
 && (Conditional AND) Short-circuit AND
 || (Conditional OR) Short-circuit OR
 =, +=, -=, *=, /=, %= (Assignment operator)
42
Operator Precedence and Associativity
The expression in the parentheses is evaluated first.
(Parentheses can be nested, in which case the
expression in the inner parentheses is executed
first.) When evaluating an expression without
parentheses, the operators are applied according to
the precedence rule and the associativity rule.

If operators with the same precedence are next to


each other, their associativity determines the order
of evaluation. All binary operators except
assignment operators are left-associative.

43
Operator Associativity

When two operators with the same


precedence are evaluated, the associativity
of the operators determines the order of
evaluation. All binary operators except
assignment operators are left-associative.
a – b + c – d is equivalent to  ((a – b) + c) – d
Assignment operators are right-associative.
Therefore, the expression
a = b += c = 5 is equivalent to a = (b += (c =
5))
44
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 45
Debugging
Logic errors are called bugs. The process of finding
and correcting errors is called debugging. A common
approach to debugging is to use a combination of
methods to narrow down to the part of the program
where the bug is located. You can hand-trace the
program (i.e., catch errors by reading the program),
or you can insert print statements in order to show
the values of the variables or the execution flow of
the program. This approach might work for a short,
simple program. But for a large, complex program,
the most effective approach for debugging is to use
a debugger utility.
46
Debugger
Debugger is a program that facilitates debugging. You can use a debugger to

Execute a single statement at a time.


Trace into or stepping over a method.
Set breakpoints.
Display variables.
Displaycall stack.
Modify variables.

47

You might also like