0% found this document useful (0 votes)
8 views

S3

Uploaded by

Dany Merhej
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

S3

Uploaded by

Dany Merhej
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

INTRODUCTION TO

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.

• The birthday is the sum of the first numbers in the sets


where the day appears
8
Problem: Guessing Birthday

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

Nested if multi-Way if-else

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

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

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

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

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

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

21
Trace if-else statement
Suppose score is 70.0 grade is C

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

22
Trace if-else statement
Suppose score is 70.0 Exit the if statement

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

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?

• The indentation indicates else matches the 1st if.


• However, the else actually matches the 2nd if.
• This situation is known as the dangling else ambiguity.
• The else clause always matches the most recent if clause
in the same block 27
Common Errors in Selection Statements
Common Error 4: Dangling else Ambiguity
• What is printed with the following code?

• 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().

• A better approach is to use the random() method in the


Math class. Invoking the method Math.random() returns a
random double value d such that 𝟎. 𝟎 ≤ 𝒅 < 𝟏. 𝟎.

• Thus, (int)(Math.random() *10) returns a random single-


digit integer (i.e., a number between 0 and 9).

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.

2. If number1 < number2, swap number1 with number2.

3. Prompt the student to answer, "What is number1 – number2?"

4. Check the student’s answer and display whether the answer is


correct.

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.

• It can be calculated by taking your weight in kilograms and


dividing it by the square of your height in meters.

• The interpretation of BMI for people 20 years or older is as


follows:

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

!(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.

The value1, ..., valueN must


have the same data type as the
value of the switch-expression.
Note that value1, ..., valueN
are constant expressions,
meaning that they cannot contain
variables in the expression,
such as 1 + x.

The resulting statements in the


case statement are executed when
the value in the case statement
matches the value of the switch-
expression.

55
Switch statement
• Full syntax for the switch statement
The keyword break is
optional. The break
statement immediately
ends the switch
statement

The default case, which is


optional, can be used to
perform actions when none of
the specified cases matches
the switch-expression

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

• The syntax is:


boolean-expression ? expression1 : expression2;
• The result of this conditional expression is expression1 if
boolean-expression is true; otherwise the result is
71
expression2.
Conditional Expressions
• The symbols ? and : appear together in a conditional
expression. They form a conditional operator called a
ternary operator because it uses three operands.
• It is the only ternary operator in Java.

• Other examples:
max = (num1 > num2) ? num1 : num2;

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

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:

• Items must match the format specifiers in


- order,
- number,
- exact type.
76
Formatting Console Output, cont.
• You can specify the width and precision in a format
specifier, as shown in the examples in Table 3.9.

77
Formatting Console Output
• Here is an other example:

• The specified width for int item 1234 is 3, which is smaller


than its actual size 4. The width is automatically increased
to 4.
• The specified width for string item Java is 2, which is
smaller than its actual size 4. The width is automatically
increased to 4.
• The specified width for double item 51.6653 is 3, but it
needs width 5 to display 51.67, so the width is
automatically increased to 5. 78
Formatting Console Output
• By default, the output is right justified.
• You can put the minus sign (-) in the format specifier to
specify that the item is left justified in the output within
the specified field. For example,
System.out.printf("%8d%8s%8.1f\n", 1234, "Java", 5.63);
System.out.printf("%-8d%-8s%-8.1f \n", 1234, "Java", 5.63);
display

where the square box  denotes a blank space.


79
Format specifiers
• For using printf, check the following settings in Elcipse

80
Operator Precedence and Associativity

• (See Appendix C, Operator Precedence Chart, for a complete list of


Java operators and their precedence.) 81
Operator Precedence and Associativity
• 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.
1. left associative

2. right associative

82
(GUI) Confirmation Dialogs
• You can use a confirmation dialog to obtain a confirmation
from the user.

• You have used showMessageDialog to display a message


dialog box and showInputDialog to display an input dialog
box.

• Occasionally it is useful to answer a question with a


confirmation dialog box. A confirmation dialog can be
created using the following statement

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,

– JOptionPane.NO_OPTION which is 1 for the No button,

– and JOptionPane.CANCEL_OPTION which is 2 for the Cancel


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

You might also like