0% found this document useful (0 votes)
4 views41 pages

3 Decisions

This document covers key concepts in Java programming, focusing on boolean data types, decision-making with if statements, and user input validation. It explains the flow of control, relational and logical operators, and the importance of proper syntax in if/else statements. Additionally, it discusses comparing strings and the significance of input validation to ensure correct data types are processed.
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)
4 views41 pages

3 Decisions

This document covers key concepts in Java programming, focusing on boolean data types, decision-making with if statements, and user input validation. It explains the flow of control, relational and logical operators, and the importance of proper syntax in if/else statements. Additionally, it discusses comparing strings and the significance of input validation to ensure correct data types are processed.
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

Decisions

CS 101, Lecture 3
Algorithms and Programming I
suggested reading:
Chapter 3
Big Java: Late Objects

This slide set was adapted from the textbook slides.


Last time
We covered:

● primitive data types


● declaration, initialization, assignment of variables
● expressions and operator precedence
● data conversions
● Math class methods
● accepting input from the user
● String objects and String class methods
2
Review question
What do the following epressions evaluate to?

3.0 / 2 + 4.1

"hi" + (1 + 1) + "u“

12 / 5 + 8 / 4

42 % 5 + 16 % 3

"cs“ + 2 + 6

2 + 6 + "cs"
3
Today
● boolean data type & boolean expressions

● Decision making with if statement

● Comparing integers, floating-point numbers, and Strings

● Testing applications

● User input validation

4
Flow of Control
● The order of statement execution is called the flow of control
○ Unless specified otherwise, the order of statement execution through a
method is linear: one after another
○ Decision (if) statements allow us to make decisions to change the flow of
control
● These decisions are based on boolean expressions (also called
conditions) that evaluate to true or false

The if statement allows a program to


carry out different actions depending on
the nature of the data to be processed.
5
Boolean Variables
● A boolean variable is often called a flag because it can be
either up (true) or down (false)

● boolean is a Java data type


• boolean failed;
• failed = true;
• Can be either true or false

6
Boolean expressions
● If conditions are boolean expressions
○ value is either true or false

● Variables of type boolean store boolean values

● Relational (comparison operators) can be used to create


boolean (relational) expressions

● Logical operators can be used to create boolean (logical)


expressions

7
Relational Operators
● A condition often uses one of Java's equality operators or
relational operators, which all return boolean results:
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to

● Note the difference between the equality operator (==) and


the assignment operator (=)

8
Relational Operator Examples

9
Relational Operator Examples

10
Relational Operators
● Relational operators are for comparing primitive data types only
● char values are compared according to their positions in the
UNICODE table
● boolean data types can only be compared using == or !=
● Since computations may generate a round-off error in 15th
decimal place in a double value, use
[Link]( calculated - expected ) <= 1E-15
Instead of
calculated == expected

● See [Link]
11
Flow of if Statement

condition
false

true

Statements if true

If the condition is true, the statements will be executed.


If the condition is false, there is nothing to do, so the if statements will be skipped,
and the first statement following the if will be executed.
12
Syntax of the if statement

if ( condition ) {
statements to be executed if condition is true;
}

Example:
if ( num > 0 ) {
[Link]( “num is positive” );
}

13
Flowchart of if/else statement

condition Statements if false


false

true

Statements if true

If the condition is true, the statements will be executed. If the condition is false, the if
statements will be skipped and the else statements will be executed. Here we are
deciding between two possible outcomes. 14
Syntax of the if/else statement
if ( condition ) {
statements to be executed if condition is true;
}
else {
statements to be executed if condition is false;
}

Example:
if ( num > 0 ) {
[Link]( “num is positive” );
}
else {
[Link]( “num is not positive” );
15
}
if/else Example
● The university bookstore has a Kilobyte Day sale every October 24, giving an 8
percent discount on all computer accessory purchases if the price is less than
$128, and a 16 percent discount if the price is at least $128.

if ( originalPrice < 128 ) {


discountRate = 0.92;
}
else {
discountRate = 0.84;
}
discountedPrice = discountRate *originalPrice;

16
if/else Exercise
Write a program that inputs an integer from the user and displays if it is even or
odd.

See [Link]

17
Nested if statements
● The statement executed as a result of an if or else clause could be another if
statement
● These are called nested if statements
● An else clause is matched to the last unmatched if (no matter what the
indentation implies)
● Braces can be used to specify the if statement to which an else clause
belongs

Example: Write a program to input three integers from the user and display their
smallest. Do not use Math class.

See [Link]
18
Finding the miminum of 3 integers
● Do we really need a nested if statement to find the minimum of 3 numbers?

// asuume num1 is the minimum


min = num1;

// check if num2 is less than min, and update min if necessary


if ( num2 < min )
min = num2;

// check if num3 is less than min, and update min if necessary


if ( num3 < min )
min = num3;

19
Comparing Floating Point Numbers
● Floating-point numbers have limited precision
● Round-off errors can lead to unexpected results
double r;
R = [Link]( 2.0 );
if ( r * r == 2.0 ) {
[Link]( "[Link](2.0) squared is 2.0" );
}
else {
[Link]( "[Link](2.0) squared is not 2.0 but " + r * r
);
}

Output:
[Link](2.0) squared is not 2.0 but 2.00000000000000044
20
The use of EPSILON
● Use a very small value to compare the difference if floating-point values are
‘close enough’
○ The magnitude of their difference should be less than some threshold
○ Mathematically, we would write that x and y are close enough if:

final double EPSILON = 1E-14;


double r;
r = [Link]( 2.0 );
if ( [Link]( r * r - 2.0 ) < EPSILON ) {
[Link]( "[Link](2.0) squared is approx. 2.0");
}

21
Logical Operators
● Boolean expressions can also use the following logical operators:

! Logical NOT
&& Logical AND
|| Logical OR

● They all take boolean operands and produce boolean results

22
Logical AND: &&
● Combining two conditions is often used in range checking
○ Is a value between two other values?

if ( temp > 0 && temp < 100 ) {


[Link]( "Liquid") ;
}

● Both sides of the && must be true for the


result to be true

23
Logical OR: ||
● If only one of two conditions need to be true, use ||

if ( balance > 100 || credit > 100 ) {


[Link]( “Accepted" );
}

● If either is true, the result is true

24
Logical NOT: !
● If you need to invert a boolean variable or comparison, precede it with !

if ( !attending || grade < 60 ) {


[Link]( “Drop?" );
}

if ( attending && !(grade < 60) ) {


[Link](“Stay");
}

25
Short Circuit Evaluation
● With the operators && and ||, the second operand is evaluated only if
needed
● Example:
5 > 3 || flag is always true (no need to know the value of the flag)

● If the left operand is sufficient to determine the result, the right operand is not
evaluated

● This is useful to avoid division by 0

if ( count != 0 && total / count > MAX ) {

26
Operator Precedence
● All operators used in Java have a defined precedence
● Generally, the precedence from highest to lowest is:
○ logical not (!),

○ arithmetic,

○ relational,

○ logical (&&, ||)

● This site has a full list of all Java operators and their precedence

27
De Morgan’s Law
● De Morgan’s law tells you how to negate && and || conditions:

○ !(A && B) is the same as !A || !B


○ !(A || B) is the same as !A && !B
● Example:

if ( !( attending && grade >= 60 ) ) { if ( !attending || grade < 60 ) )


[Link]( “Drop?" ); {
} [Link]( “Drop?" );
}

Remark: To simplify conditions with negations of && or ||


expressions, it is usually a good idea to apply De Morgan’s Law
to move the negations to the innermost level. 28
Boolean Operator Examples

29
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Remarks on using Boolean operators

● There is no need to compare a Boolean variable with true


○ frozen == true = frozen

● It is clearer to use ! than to compare with a false


○ frozen == false = !frozen

● Prefer these Read as:


Read as:
if frozen if NOT frozen

if ( !frozen ) {
if ( frozen ) { …
… }
}
30
Indent your code!
● Indenting consistently makes code much easier for humans to follow

31
Comparing Strings
● We cannot use the == operator to compare two strings
● Syntactically, the following statement is correct:
if ( str1 == str2 )
but what is being compared are the references (locations), and not the
strings they reference
● String class gives us the following methods for comparing Strings:
○ boolean equals( String str )
○ boolean equalsIgnoreCase( String str)
○ int compareTo( String str )

32
Lexicographical Order
● To compare Strings in “dictionary” order
○ When compared using compareTo, string1 comes:
■ Before string2 if [Link]( string2 ) < 0
■ After string2 if [Link]( string2 ) > 0
■ Equal to string2 if [Link]( string2 ) == 0
○ Notes
■ All UPPERCASE letters come before lowercase
■ ‘space’ comes before all other printable characters
■ Digits (0-9) come before all letters

33
Flowchart of Multiway branching

True
> 8.0? Most Structures Fall
False
>= 7.0? True Many Buildings Destroyed
False
True Many buildings considerably
>= 6.0?
damaged, some collapse
False
True Damage to poorly constructed
>= 4.5?
buildings
False
No destruction of buildings

34
if/else if multiway branching
if ( richter >= 8.0 ) { // Handle the ‘special case’ first
[Link]("Most structures fall");
}
else if ( richter >= 7.0 ) {
[Link]("Many buildings destroyed");
}
else if ( richter >= 6.0 ) {
[Link]("Many buildings damaged, some collapse");
}
else if ( richter >= 4.5 ) {
[Link]("Damage to poorly constructed buildings");
}
else { // so that the ‘general case’ can be handled last
[Link]("No destruction of buildings");
} 35
What is wrong with this code?
if ( richter >= 8.0 ) { // Handle the ‘special case’ first
[Link]("Most structures fall");
}
if ( richter >= 7.0 ) {
[Link]("Many buildings destroyed");
}
if ( richter >= 6.0 ) {
[Link]("Many buildings damaged, some collapse");
}
if ( richter >= 4.5 ) {
[Link]("Damage to poorly constructed buildings");
}
else { // so that the ‘general case’ can be handled last
[Link]("No destruction of buildings");
} 36
Input Validation
● Accepting user input is dangerous
○ The user may input invalid characters or values
○ For example, if we need to input an integer, how do we validate that
the value entered is an integer?
○ Scanner class can help!
■ The hasNextInt() method:
● Checks the value input by the user, and returns
○ True if the value is an integer
○ False if not
○ The value can then be validated against the range of appropriate
values

37
Exercise
Write a program, [Link], that inputs a score from the user, and outputs
the letter grade according to the following criteria:

90-100 A
80-89 B
70-79 C
60-69 D
0-59 F

See [Link] and [Link]

38
Tracing code
● Hand-tracing helps you understand whether a program works correctly
● Create a table of key variables
○ Use pencil and paper to track their values

● Works with pseudocode or code


○ Carry out each instruction in the sequence

● Use example input values that:


○ You know what the correct outcome should be
○ Will test each branch of your code

39
Character testing methods
● The Character class has a number of useful methods that return information
about the properties of chars
● The methods take a character as a parameter and return a boolean result
● The methods are static method, meaning they are called (invoked) using the
name of the class, followed by the name of the method

if ( [Link]( ch ) ) {
...
}

40
Useful Character class methods

41

You might also like