2/23/2014
1
CSCS110110: PROGRAMMING : PROGRAMMING
LANGUAGE ILANGUAGE I
Lecture 5: DecisionsComputer Science
Department
Lecture Contents:
L. Shaykhah Aldosari,2014
2
� The Boolean Type
� Comparison Operators
� Control Structures
� if statement: Single-selection statement.
� if…else statement: Double-selection statement.
� switch statement: Multiple-selection statement.
� Logical Operators
2/23/2014
2
The Boolean Type and Operators
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.
boolean b = (1 > 2);
3
L. Shaykhah Aldosari,2014
Comparison Operators4
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
Equality
operators
Relational
operators
L. Shaykhah Aldosari,2014
2/23/2014
3
Example 5
L. Shaykhah Aldosari,2014
Control Structures
� Three types of selection statements.1- if statement:
� Performs an action, if a condition is true; skips it, if false. � Single-selection statement—selects or ignores a single action (or
group of actions).
2- if…else statement: � Performs an action if a condition is true and performs a different
action if the condition is false. � Double-selection statement—selects between two different actions
(or groups of actions).
3- switch statement� Performs one of several actions, based on the value of an
expression.� Multiple-selection statement—selects among many different actions
(or groups of actions).
6
L. Shaykhah Aldosari,2014
2/23/2014
4
1- if Single-Selection Statement
� PseudocodeIf student’s grade is greater than or equal to 60
Print “Passed”
� If the condition is false, the Print statement is ignored, and the next pseudocode statement in order is performed.
� If in Java:if ( studentGrade >= 60 )
System.out.println( "Passed" );
7
L. Shaykhah Aldosari,2014
1- if Single-Selection Statement (Cont.)
L. Shaykhah Aldosari,2014
8
2/23/2014
5
1- if Single-Selection Statement
(example):9
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.?
L. Shaykhah Aldosari,2014
The answer:10
L. Shaykhah Aldosari,2014
2/23/2014
6
2- if…else Double-Selection Statement
� if…else double-selection statement—specify an action to perform when the condition is true and a different action when the condition is false.
� PseudocodeIf student’s grade is greater than or equal to 60
Print “Passed”Else
Print “Failed”
� If…Else in Java:if ( grade >= 60 )
System.out.println( "Passed" );else
System.out.println( "Failed" );
11
L. Shaykhah Aldosari,2014
2- if…else Double-Selection Statement
(Cont.)
L. Shaykhah Aldosari,2014
12
2/23/2014
7
2- if…else Double-Selection Statement
(Cont.)
� Conditional operator (?:)—shorthand if…else.
� Ternary operator (takes three operands)
� Operands and ?: form a conditional expression
� Operand to the left of the ? is a boolean expression—evaluates to a boolean value (true or false)
� Second operand (between the ? and :) is the value if the booleanexpression is true
� Third operand (to the right of the :) is the value if the booleanexpression evaluates to false.
13
L. Shaykhah Aldosari,2014
2- if…else Double-Selection Statement
(Cont.)
� Example:System.out.println(
studentGrade >= 60 ? "Passed" : "Failed" );
� Evaluates to the string "Passed" if the boolean expression studentGrade >= 60 is true and to the string "Failed" if it is false.
14
L. Shaykhah Aldosari,2014
2/23/2014
8
2- if…else Double-Selection Statement
(Cont.)
� Can test multiple cases by placing if…else statements inside other if…else statements to create nested if…elsestatements.
� Pseudocode:If student’s grade is greater than or equal to 90
Print “A”else
If student’s grade is greater than or equal to 80Print “B”
else If student’s grade is greater than or equal to 70
Print “C”else
If student’s grade is greater than or equal to 60 Print “D”
elsePrint “F”
15
L. Shaykhah Aldosari,2014
2- if…else Double-Selection Statement
(Cont.)
� This pseudocode may be written in Java asif ( studentGrade >= 90 )
System.out.println( "A" );else
if ( studentGrade >= 80 )System.out.println( "B" );
elseif ( studentGrade >= 70 )
System.out.println( "C" );else
if ( studentGrade >= 60 )System.out.println( "D" );
elseSystem.out.println( "F" );
� If studentGrade >= 90, the first four conditions will be true, but only the statement in the if part of the first if…elsestatement will execute. After that, the else part of the “outermost” if…else statement is skipped.
16
L. Shaykhah Aldosari,2014
2/23/2014
9
2- if…else Double-Selection Statement
(Cont.)
� Most Java programmers prefer to write the preceding nested if…else statement as
if ( studentGrade >= 90 )System.out.println( "A" );
else if ( studentGrade >= 80 )System.out.println( "B" );
else if ( studentGrade >= 70 )System.out.println( "C" );
else if ( studentGrade >= 60 )System.out.println( "D" );
elseSystem.out.println( "F" );
� The two forms are identical except for the spacing and indentation, which the compiler ignores.
17
L. Shaykhah Aldosari,2014
2- if…else Double-Selection Statement
(Cont.)
� The Java compiler always associates an else with the immediately preceding if unless told to do otherwise by the placement of braces ({ and }).
� Referred to as the dangling-else problem.
� The following code is not what it appears:if ( x > 5 )
if ( y > 5 )System.out.println( "x and y are > 5" );
elseSystem.out.println( "x is <= 5" );
� Beware! This nested if…else statement does not execute as it appears. The compiler actually interprets the statement as
if ( x > 5 )if ( y > 5 )
System.out.println( "x and y are > 5" );else
System.out.println( "x is <= 5" );
18
L. Shaykhah Aldosari,2014
2/23/2014
10
2- if…else Double-Selection Statement
(Cont.)
� To force the nested if…else statement to execute as it was originally intended, we must write it as follows:
if ( x > 5 ) {
if ( y > 5 )System.out.println( "x and y are > 5" );
}else
System.out.println( "x is <= 5" );
� The braces indicate that the second if is in the body of the first and that the else is associated with the first if.
19
L. Shaykhah Aldosari,2014
2- if…else Double-Selection Statement
(Cont.)
� The if statement normally expects only one statement in its body.
� To include several statements in the body of an if (or the body of an else for an if…else statement), enclose the statements in braces.
� Statements contained in a pair of braces form a block.
� A block can be placed anywhere that a single statement can be placed.
� Example: A block in the else part of an if…else statement:if ( grade >= 60 )
System.out.println("Passed");else{
System.out.println("Failed");System.out.println("You must take this course again.");
}
20
L. Shaykhah Aldosari,2014
2/23/2014
11
Problem: An Improved Math Learning
Tool
L. Shaykhah Aldosari,2014
21
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. After the student types the
answer, the program displays whether the answer is
correct.
The answer:
L. Shaykhah Aldosari,2014
22
2/23/2014
12
23
L. Shaykhah Aldosari,2014
Problem: Body Mass Index
L. Shaykhah Aldosari,2014
24
Body Mass Index (BMI) is a measure of health on
weight. It can be calculated by taking your weight in
kilograms and dividing by the square of your height in
meters. The interpretation of BMI for people 16 years
or older is as follows:
BMI Interpretat ion Below 18.5 Underweight
18.5-24.9 Normal 25.0-29.9 Overweight Above 30.0 Obese
2/23/2014
13
The answer:
L. Shaykhah Aldosari,2014
25
L. Shaykhah Aldosari,2014
26
2/23/2014
14
3- switch Multiple-Selection Statement
� switch multiple-selection statement performs
different actions based on the possible values of a
constant integral expression of type byte, short, int or char.
27
L. Shaykhah Aldosari,2014
3- switch Multiple-Selection Statement
(Cont.)
� The switch statement consists of a block that contains a sequence of case labels and an optional default case.
� The program evaluates the controlling expression in the parentheses following keyword switch.
� The program compares the controlling expression’s value (which must evaluate to an integral value of type byte, char, short or int) with each case label.
� If a match occurs, the program executes that case’s statements.
� The break statement causes program control to proceed with the first statement after the switch.
28
L. Shaykhah Aldosari,2014
2/23/2014
15
3- switch Multiple-Selection Statement
(Cont.)� switch does not provide a mechanism for testing ranges of
values—every value must be listed in a separate case label.
� Note that each case can have multiple statements.
� switch differs from other control statements in that it does not require braces around multiple statements in a case.
� Without break, the statements for a matching case and subsequent cases execute until a break or the end of the switch is encountered. This is called “falling through.”
� If no match occurs between the controlling expression’s value and a case label, the default case executes.
� If no match occurs and there is no default case, program control simply continues with the first statement after the switch.
29
L. Shaykhah Aldosari,2014
3- switch Multiple-Selection Statement
(Cont.)
L. Shaykhah Aldosari,2014
30
2/23/2014
16
Be careful! 31
L. Shaykhah Aldosari,2014
3- switch Multiple-Selection Statement
(Cont.)
� When using the switch statement, remember that each case must contain a constant integral expression.
� An integer constant is simply an integer value.
� In addition, you can use character constants—specific characters in single quotes, such as 'A', '7' or '$'—which represent the integer values of characters.
� The expression in each case can also be a constant variable—a variable that contains a value which does not change for the entire program. Such a variable is declared with keyword final.
� Java has a feature called enumerations. Enumeration constants can also be used in case labels.
32
L. Shaykhah Aldosari,2014
2/23/2014
17
3- switch Multiple-Selection Statement
(Cont.)
� As of Java SE 7, you can use Strings in a switch statement’s controlling expression and in case labels as in:
� switch( city ){
case "Maynard":zipCode = "01754";break;
case "Marlborough":zipCode = "01752";break;
case "Framingham":zipCode = "01701";break;
} // end switch
�
33
L. Shaykhah Aldosari,2014
Problem: Chinese Zodiac
Write a program that prompts the user to enter a year
and displays the animal for the year.
34
rat
ox
tiger
rabbit
dragon
snake horse
sheep
monkey
rooster
dog
pig 0: monkey
1: rooster 2: dog 3: pig 4: rat
5: ox 6: t iger 7: rabbit 8: dragon 9: snake
10: horse 11: sheep
year % 12 =
L. Shaykhah Aldosari,2014
2/23/2014
18
The answer: 35
L. Shaykhah Aldosari,2014
Logical Operators
� Java’s logical operators enable you to form more complex conditions by combining simple conditions.
� The logical operators are � && (conditional AND)
� || (conditional OR)
� & (boolean logical AND)
� | (boolean logical inclusive OR)
� ^ (boolean logical exclusive OR)
� ! (logical NOT).
� [Note: The &, | and ^ operators are also bitwise operators when they are applied to integral operands.]
36
L. Shaykhah Aldosari,2014
2/23/2014
19
Logical Operators (Cont.)
� The & (conditional AND) operator ensures that two conditions are both true before choosing a certain path of execution.
37
L. Shaykhah Aldosari,2014
Logical Operators (Cont.)
� The || (conditional OR) operator ensures that either or both of two conditions are true before choosing a certain path of execution.
38
L. Shaykhah Aldosari,2014
2/23/2014
20
Logical Operators (Cont.)
� The parts of an expression containing && or ||operators are evaluated only until it’s known
whether the condition is true or false. T
� This feature of conditional AND and conditional
OR expressions is called short-circuit evaluation.
39
L. Shaykhah Aldosari,2014
Logical Operators (Cont.)
� The boolean logical AND (&&&&) and boolean logical inclusive OR (||||) operators are identical to the &&and || operators, except that the & and | operators
always evaluate both of their operands (i.e., they do not perform short-circuit evaluation).
� This is useful if the right operand of the boolean
logical AND or boolean logical inclusive OR
operator has a required side effect—a modification
of a variable’s value.
40
L. Shaykhah Aldosari,2014
2/23/2014
21
Logical Operators (Cont.)
� A simple condition containing the boolean logical
exclusive OR (^̂̂̂) operator is true if and only if one of its operands is true and the other is
false.
41
L. Shaykhah Aldosari,2014
Logical Operators (Cont.)
� The ! (logical NOT, also called logical negation or logical complement) operator “reverses” the meaning of a condition.
� The logical negation operator is a unary operator that has only a single condition as an operand.
42
L. Shaykhah Aldosari,2014
2/23/2014
22
Logical Operators (Cont.)
� The %b format specifier displays the word “true” or the word “false” based on a booleanexpression’s value.
43
L. Shaykhah Aldosari,2014
Logical Operators :Examples44
System.out.println("Is " + number + " divisible by 2
and 3? " +
((number % 2 == 0) && (number % 3 == 0)));
System.out.println("Is " + number + " divisible by 2
or 3? " +
((number % 2 == 0) || (number % 3 == 0)));
System.out.println("Is " + number +
" divisible by 2 or 3, but not both? " +
((number % 2 == 0) ^ (number % 3 == 0))); L. Shaykhah Aldosari,2014
2/23/2014
23
The & and | Operators: Examples:45
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++)?
L. Shaykhah Aldosari,2014
46
L. Shaykhah Aldosari,2014
2/23/2014
24
Text Book:
Java : how to program , by P.J. Deitel, H.M. Deitel. -- 9th ed.
Sections:
4.4, 4.5, 4.6, 5.6 , 5.8.
That’s all for today !!47
L. Shaykhah Aldosari,2014