SlideShare a Scribd company logo
1 of 54
4. More Control Structures and
Types
4.1 Logical (Conditional) AND, OR, and NOT
4.2 Nested Ifs and the Switch Statement
4.3 The For and Do-While Loops
4.4 Additional Primitive Types
4.5 Using the Math Library
4.6 Solving Problems with Java: An Iterative
Development Cycle
Objectives
• Learn useful selection and repetition
statement
• Use primitive types and operators
• Use the Math library
• Build software using an iterative
development cycle
Logical Operators
• Boolean expressions can use logical (conditional)
! Logical NOT
&& Logical AND
|| Logical OR
• They all take boolean operands and produce
boolean results
• Logical NOT (Conditional Complement) is a
unary operator (one operand), but the other two
are binary operators (two operands)
Logical Operators
• Conditions in selection statements and loops can
use logical operators to form complex expressions
if (b >= a && c >= a)
min = a;
if (a >= b && c >= b)
min = b;
if (a >= c && b >= c)
min = c;
• Logical operators have precedence relationship
between themselves and other operators
Symbol Meaning Example
&& conditional AND (age > 20) && (age < 35)
|| conditional OR (height > 78.5) || (weight > 300)
Figure 4.2 Conditional Operators
age age > 20 age < 35 age > 20 && age < 35
10 false true false
25 true true true
40 true false false
Figure 4.3 Evaluating an example of a conditional AND expression
A B A && B
true true true
true false false
false (don't care) false
Figure 4.4 Evaluating a conditional AND expression
height weight height > 78.5 weight > 300 (height>78.5) || (weight>300)
62 125 false false false
80 250 true false true
72 310 false true true
80 325 true true true
Figure 4.5 Evaluating an example of a conditional OR expression
A B A || B
true (don't care) true
false true true
false false false
Figure 4.6 Evaluating a condition OR expression
A !A
true false
false true
Figure 4.7 Evaluating a logical complement expression
Figure 4.8 Operator precedence*
Highest
NOT! !
multiplicative * / %
additive + -
relational < > <= >=
equality == !=
conditional AND &&
conditional OR ||
assignment = += -= *= /= %=
Lowest
if (score >= 60 && score < 80)
System.out.println("Score " + score + " receives a C");
else
System.out.println("Score " + score + " receives a B or an A");
Figure 4.9 If-else statement to choose between two alternatives
Nested If Statements
• The if-true-statement and if-false-statement of an
if statement could be another if statement
• These are called nested if statements
if (a >= b)
if (b >= c) min = c;
else min = b;
else
if (a >= c) min = c;
else min = a;
• An else clause is matched to the last unmatched if
(no matter what the indentation implies)
Figure 4.10 Nested if-else statement to choose among three alternatives
if (score >= 60 && score < 80)
System.out.println("Score " + score + " receives a C");
else if (score >=80 && score < 90)
System.out.println("Score " + score + " receives a B");
else
System.out.println("Score " + score + " receives an A");
Figure 4.11 Improved version of Figure 4.10
if (score >= 60 && score < 80)
System.out.println("Score " + score + " receives a C");
else if (score >=80 && score < 90)
System.out.println("Score " + score + " receives a B");
else if (score >= 90 && score <= 100)
System.out.println("Score " + score + " receives an A");
Figure 4.12 Flow chart for nested if-else statements
Last?
Last false code
...
Last true code
True
False
False
Test1?
Test2?
Test1 true code
Test2 true code
True
True
False
False
Figure 4.13 Incorrect attempt to pair an else with an if
if (score >= 60)
if (score >= 80)
System.out.println("You got a B or an A");
else
System.out.println("You got a D or an F"); // Wrong pairing
Figure 4.14 Corrected pairing of else and if
if (score >= 60)
if (score >= 80)
System.out.println("You got a B or an A");
else
System.out.println("You got a C"); // Correct pairing
Figure 4.15 Figure 4.13 rewritten as an if-else with nested if
if (score >= 60) {
if (score >= 80)
System.out.println("You got a B or an A");
}
Else
// Paired to first 'if'
System.out.println("You got a D or an F");
The Switch Statement
• The switch statement provides another means to
decide which statement to execute next
• The switch statement evaluates an expression, then
attempts to match the result to one of several
possible cases
• Each case contains a value and a list of statements
• The flow of control transfers to statement list
associated with the first value that matches
The Switch Statement
• A switch statement can have an optional default
case which has no associated value
• If the default case is present, control will transfer
to it if no other case value matches
• The default case can be positioned anywhere in
the switch, it is usually placed at the end
• If there is no default case, and no other value
matches, control falls through to the next
statement after the switch
The Switch Statement
• Often a break statement is used as the last
statement in each case’s statement list
• A break statement causes control to transfer to the
end of the switch statement
• If a break statement is not used, the flow of
control will continue into the next case
• The expression of a switch statement must result
in an integral data type, like an integer or character
• You cannot perform relational checks with a
switch staement
Figure 4.16 An example of a switch statement
switch(mark) {
case 0:
case 1:
case 2:
case 3:
case 4: System.out.println("F");
break;
case 5: System.out.println("D");
break;
case 6:
case 7: System.out.println("C");
break;
case 8: System.out.println("B");
break;
case 9:
case10: System.out.println("A");
break;
default:System.out.println("Incorrect score");
}
The For Statement
• The for statement has the following syntax:
for ( initialization ; condition ; increment )
statement ;
• The initialization is executed once before the loop
begins
• The statement is executed until the condition
becomes false
• The increment portion is executed at the end of
each iteration
The For Statement
• The for statement is equivalent to the following
while loop structure
initialization ;
while ( condition )
{
statement ;
increment ;
}
• Like a while loop, the condition of a for loop is
tested prior to executing the loop body
• Therefore, the body of a for loop can be
executed zero or more times
Figure 4.17 A for statement for the sum 1+2+3+4
int sum = 0;
for (int i = 1; i <= 4; i++)
sum += i;
initialize i = 1
test 1 <= 4 is true
execute body sum += 1 (result: sum = 0 + 1 = 1)
update i++ (result: i = 2)
test 2 <= 4 is true
execute body sum += 2 (result: sum = 1 + 2 = 3)
update i++ (result: i = 3)
test 3 <= 4 is true
execute body sum += 3 (result: sum = 3 + 3 = 6)
update i++ (result: i + 4)
test 4 <= 4 is true
execute body sum += 4 (result: sum = 6 + 4 = 10)
update i++ (result: i = 5)
test 5 <= 4 is false
Figure 4.18 Trace of execution of the for loop of Figure 4.17
Figure 4.19 A for statement for the sum 1+3+5+7+9
int sum = 0;
for (int i = 1; i < 10; i += 2)
sum += i;
Figure 4.20 A for statement for the sum 4+3+2+1
int sum = 0;
for (int i = 4; i >= l; i--)
sum += i;
Figure 4.21 Declaring an index variable before the for loop
int i; // declare loop index
int sum = 0;
for (i = 4; i >= 1; i--) // initialize loop index
sum += i;
...
i += 17; // use variable i
Examples
• TwelveDays.java (extra)
• Diamond.java (extra)
• Growth.java
• Mortgage.java (extra)
The StringTokenizer Class
• StringTokenizer(String str)
Constructor. Creates a new StringTokenizer object to parse str based
on white space
• StringTokenizer(String str, String delimiter)
Constructor. Creates a new StringTokenizer object to parse str based
on specified set of delimiteds
• int countTokens()
Returns the number of token still left to be processed in the string
• boolean hasMoreTokens()
Returns true if there are tokens still left to be processed in the string
• String nextToken()
Returns the next token in the string
Figure 4.22 Syntax for the do-while statement
do
statement
while (condition) ;
Do-while Statement
• A do-while statement checks the condition after
executing the loop body
• The loop body of a do-while statement is executed
at least once
• Do-while statements are suitable for writing loops
that are executed at least once
• DoGrowth.java
• Babylonian.java (extra)
Figure 4.23 Pseudocode for example 4.5 enhancement
do {
Compute balance as in Example 4.5
Ask the user -- Repeat or Quit?
} while (User chooses to repeat);
The char Type
• Java uses Unicode charater set (16 bits)
• ASCII, American Standard Code for Information
Interchange, is a seven-bit code used by other
language like C and C++
• ASCII is a subset of Unicode
• Keyword char to denote character type
• Character constants are quoted in single quotes,
e.g. ‘A’
• Ascii.java
Escape Sequence
• Escape sequence: preceding certain character with
the escape character  for special meaning
• The newline, 'n', positions the next output at
the start of the next line
• The return, 'r', positions the next output at the
start of the curent line
• The backspace, 'b', positions the next output
one character to the left
• The tab, 't', position the next output at the next
tab position
Escape Sequence
• The escape needs to be "escaped" when quoted
like '' and ""
• The single quote character must be "escaped" in
single quotes like '''
• The double quote must be "escaped" in double
quotes like ””This is a quote”"
• Special.java
backlash
Special
Character
Meaning
n newline, move to the start of the next line
t tab
b backspace
r return, move to the start of the current line
" double quote
n newline, move to the start of the next line
Figure 4.24 Escape sequences for special characters
The byte, short, and long Types
• byte: one byte = 8 bits, range from -128 to 127
• short: two bytes = 16 bits
– range from -32,768 to 32,767
• int: four bytes = 32 bits
– range from -2,147,483,648 to 2,147,483,647
• long: eight bytes = 64 bits
– range 9,223,372,036,854,808 to 9,223,372,036,854,807
• int is the default for integer constant
• Integer constants can be made long by adding the
suffix l or L
The float Type
• float: four bytes = 32 bits
– Exponent can range from -45 to 48
– Min ~ -3.4E+38 with seven significant digits
– Max ~ 3.4E+38 with seven significant digits
• double: eight bytes = 64 bits
– Exponent can range from -324 to 308
– Min ~ -1.7E+308 with 16 significant digits
– Max ~ 1.7E+308 with 16 significant digits
• double is the default for real constants
• Make a number float by adding an f or F suffix
float good = 4.25f; // valid
float ok = (float)4.25; // valid
float bad = 4.25; // invalid
The Math Class
• In java.lang package
• Two static constants: E (base of natural log) and
PI (ratio of circumference of a circle to its
diameter)
• General functions
abs - absolute value
ceil - ceiling, smallest integer >= argument
floor - flooring, greatest integer <= argument
round - rounding, integer closest to argument
max - maximum of the two arguments
min - minimum of the two arguments
The Math Class
• Simple mathematical operations
sqrt(double a) - Return the square root of the argument
pow(double a, double b) - Returns of value of the first
argument raised to the power of the second argument
log(double a) - Returns the natural logarithm (base e) of
a double value
exp(double a) - Returns the exponential number e (i.e.,
2.718...) raised to the power of a double value
• Random number
random() - Returns a double value with a positive sign,
greater than or equal to 0.0 and less than 1.0
The Math Class
• Trigonometric functions
sin, cos, tan - sine, cosine, and tangent
asin, acos, atan- arc-sine, arc-cosine, and arc-tangent
atan2(double a, double b) - Returns the theta
component in the polar coordinates (r, theta)
corresponding to the point (b, a) in Cartesian
coordinates
• Degree/Radian conversion
toDegrees(double angrad) - Converts an angle in
radians to the equivalent angle measured in degrees
toRadians(double angdeg) - Converts an angle in
degrees to the equivalent angle measured in radians
The Math Class
• Library.java
• Toss.java
• CoinToss.java
Figure 4.25 Size of the reward given each day
1
1
2
4
8
12 16
16
8
4
2
Days
Figure 4.26 Using random numbers to represent heads and tails
0.0 0.5 1.0
HHHHHHHHHHHHHHHHHTTTTTTTTTTTTTTTTTT
Heads Tails
Iterative Development Cycle
• First iteration - CovertMenu.java (with stubs for
methods)
• Second iteration - CovertFromMetric.java
(implement MetricToEnglish())
• Third iteration - Convert.java (implement
EnglishToMetric())
Figure 4.27 Iterative problem-solving process
Formulate the problem;
do {
Develop pseudocode;
Implement pseudocode in Java program;
Test program;
while (More subproblems to refine);
Figure 4.28 Top-level Pseudocode
do [
Display the menu;
Get the user's choice;
Execute the user's choice;
} while (user does not choose to quit);
Figure 4.29 Pattern for a menu-driven application
do {
System.out.println();
System.out.println("Choose from the following list");
System.out.println("1. Convert from meters to yds,ft,in");
System.out,println("2. Convert from yds,ft,in to meters");
System.out.println("3. Quit");
int choice = Io.readInt("Enter your choice, 1, 2 or 3");
switch (choice) {
case 1:
MetricToEnglish();
break;
case 2:
EnglishToMetric();
break;
case 3: System.out.println("Bye, Have a nice day");
}
} while (choice != 3);
Figure 4.30 Pseudocode for the MetricToEnglish method
Input the number of meters, x, to convert;
Convert x meters to y yards;
Separate y into yInteger yards and yFraction yards;
Convert yFraction yards to f feet.
Separate f into fInteger feet and fFraction feet.
Convert fFraction feet to i inches.
Display the output.
Figure 4.31 Refinement:Display the output
if (yInteger > 0)
if (yInteger <= 1) Display yInteger yard;
else Display yInteger yards;
if (fInteger > 0)
if (fInteger <= 1) Display fInteger foot;
else Display fInteger feet;
if (i >0)
if (i <= 1) Display i inch;
else Display i inches;
if (yInteger == 0 && fInteger == 0 && i == 0)
Display 0 yards;
Figure 4.32 Pseudocode for the EnglishToMetric method
Input yards, feet, and inches to convert;
Convert to inches;
Convert inches to meters;
Output the result;

More Related Content

Similar to java switch

Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operatorsmcollison
 
CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptSanjjaayyy
 
3. control statements
3. control statements3. control statements
3. control statementsamar kakde
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsTech
 
The Ultimate FREE Java Course Part 1
The Ultimate FREE Java Course Part 1The Ultimate FREE Java Course Part 1
The Ultimate FREE Java Course Part 1Coursetro Com
 
java - Introduction , control structures
java - Introduction , control structuresjava - Introduction , control structures
java - Introduction , control structuressandhyakiran10
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptxssuserfb3c3e
 
Acm aleppo cpc training introduction 1
Acm aleppo cpc training introduction 1Acm aleppo cpc training introduction 1
Acm aleppo cpc training introduction 1Ahmad Bashar Eter
 
Java learning
Java learningJava learning
Java learningmoew3
 
Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2alish sha
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxLikhil181
 
Csphtp1 05
Csphtp1 05Csphtp1 05
Csphtp1 05HUST
 

Similar to java switch (20)

Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operators
 
CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.ppt
 
What is c
What is cWhat is c
What is c
 
3. control statements
3. control statements3. control statements
3. control statements
 
05 operators
05   operators05   operators
05 operators
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming Concepts
 
Introduction to c part -1
Introduction to c   part -1Introduction to c   part -1
Introduction to c part -1
 
The Ultimate FREE Java Course Part 1
The Ultimate FREE Java Course Part 1The Ultimate FREE Java Course Part 1
The Ultimate FREE Java Course Part 1
 
Control structure
Control structureControl structure
Control structure
 
04.ppt
04.ppt04.ppt
04.ppt
 
java - Introduction , control structures
java - Introduction , control structuresjava - Introduction , control structures
java - Introduction , control structures
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptx
 
Acm aleppo cpc training introduction 1
Acm aleppo cpc training introduction 1Acm aleppo cpc training introduction 1
Acm aleppo cpc training introduction 1
 
Java learning
Java learningJava learning
Java learning
 
Chapter3
Chapter3Chapter3
Chapter3
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
Basic_Java_02.pptx
Basic_Java_02.pptxBasic_Java_02.pptx
Basic_Java_02.pptx
 
Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptx
 
Csphtp1 05
Csphtp1 05Csphtp1 05
Csphtp1 05
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Recently uploaded (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

java switch

  • 1. 4. More Control Structures and Types 4.1 Logical (Conditional) AND, OR, and NOT 4.2 Nested Ifs and the Switch Statement 4.3 The For and Do-While Loops 4.4 Additional Primitive Types 4.5 Using the Math Library 4.6 Solving Problems with Java: An Iterative Development Cycle
  • 2. Objectives • Learn useful selection and repetition statement • Use primitive types and operators • Use the Math library • Build software using an iterative development cycle
  • 3. Logical Operators • Boolean expressions can use logical (conditional) ! Logical NOT && Logical AND || Logical OR • They all take boolean operands and produce boolean results • Logical NOT (Conditional Complement) is a unary operator (one operand), but the other two are binary operators (two operands)
  • 4. Logical Operators • Conditions in selection statements and loops can use logical operators to form complex expressions if (b >= a && c >= a) min = a; if (a >= b && c >= b) min = b; if (a >= c && b >= c) min = c; • Logical operators have precedence relationship between themselves and other operators
  • 5. Symbol Meaning Example && conditional AND (age > 20) && (age < 35) || conditional OR (height > 78.5) || (weight > 300) Figure 4.2 Conditional Operators
  • 6. age age > 20 age < 35 age > 20 && age < 35 10 false true false 25 true true true 40 true false false Figure 4.3 Evaluating an example of a conditional AND expression
  • 7. A B A && B true true true true false false false (don't care) false Figure 4.4 Evaluating a conditional AND expression
  • 8. height weight height > 78.5 weight > 300 (height>78.5) || (weight>300) 62 125 false false false 80 250 true false true 72 310 false true true 80 325 true true true Figure 4.5 Evaluating an example of a conditional OR expression
  • 9. A B A || B true (don't care) true false true true false false false Figure 4.6 Evaluating a condition OR expression
  • 10. A !A true false false true Figure 4.7 Evaluating a logical complement expression
  • 11. Figure 4.8 Operator precedence* Highest NOT! ! multiplicative * / % additive + - relational < > <= >= equality == != conditional AND && conditional OR || assignment = += -= *= /= %= Lowest
  • 12. if (score >= 60 && score < 80) System.out.println("Score " + score + " receives a C"); else System.out.println("Score " + score + " receives a B or an A"); Figure 4.9 If-else statement to choose between two alternatives
  • 13. Nested If Statements • The if-true-statement and if-false-statement of an if statement could be another if statement • These are called nested if statements if (a >= b) if (b >= c) min = c; else min = b; else if (a >= c) min = c; else min = a; • An else clause is matched to the last unmatched if (no matter what the indentation implies)
  • 14. Figure 4.10 Nested if-else statement to choose among three alternatives if (score >= 60 && score < 80) System.out.println("Score " + score + " receives a C"); else if (score >=80 && score < 90) System.out.println("Score " + score + " receives a B"); else System.out.println("Score " + score + " receives an A");
  • 15. Figure 4.11 Improved version of Figure 4.10 if (score >= 60 && score < 80) System.out.println("Score " + score + " receives a C"); else if (score >=80 && score < 90) System.out.println("Score " + score + " receives a B"); else if (score >= 90 && score <= 100) System.out.println("Score " + score + " receives an A");
  • 16. Figure 4.12 Flow chart for nested if-else statements Last? Last false code ... Last true code True False False Test1? Test2? Test1 true code Test2 true code True True False False
  • 17. Figure 4.13 Incorrect attempt to pair an else with an if if (score >= 60) if (score >= 80) System.out.println("You got a B or an A"); else System.out.println("You got a D or an F"); // Wrong pairing
  • 18. Figure 4.14 Corrected pairing of else and if if (score >= 60) if (score >= 80) System.out.println("You got a B or an A"); else System.out.println("You got a C"); // Correct pairing
  • 19. Figure 4.15 Figure 4.13 rewritten as an if-else with nested if if (score >= 60) { if (score >= 80) System.out.println("You got a B or an A"); } Else // Paired to first 'if' System.out.println("You got a D or an F");
  • 20. The Switch Statement • The switch statement provides another means to decide which statement to execute next • The switch statement evaluates an expression, then attempts to match the result to one of several possible cases • Each case contains a value and a list of statements • The flow of control transfers to statement list associated with the first value that matches
  • 21. The Switch Statement • A switch statement can have an optional default case which has no associated value • If the default case is present, control will transfer to it if no other case value matches • The default case can be positioned anywhere in the switch, it is usually placed at the end • If there is no default case, and no other value matches, control falls through to the next statement after the switch
  • 22. The Switch Statement • Often a break statement is used as the last statement in each case’s statement list • A break statement causes control to transfer to the end of the switch statement • If a break statement is not used, the flow of control will continue into the next case • The expression of a switch statement must result in an integral data type, like an integer or character • You cannot perform relational checks with a switch staement
  • 23. Figure 4.16 An example of a switch statement switch(mark) { case 0: case 1: case 2: case 3: case 4: System.out.println("F"); break; case 5: System.out.println("D"); break; case 6: case 7: System.out.println("C"); break; case 8: System.out.println("B"); break; case 9: case10: System.out.println("A"); break; default:System.out.println("Incorrect score"); }
  • 24. The For Statement • The for statement has the following syntax: for ( initialization ; condition ; increment ) statement ; • The initialization is executed once before the loop begins • The statement is executed until the condition becomes false • The increment portion is executed at the end of each iteration
  • 25. The For Statement • The for statement is equivalent to the following while loop structure initialization ; while ( condition ) { statement ; increment ; } • Like a while loop, the condition of a for loop is tested prior to executing the loop body • Therefore, the body of a for loop can be executed zero or more times
  • 26. Figure 4.17 A for statement for the sum 1+2+3+4 int sum = 0; for (int i = 1; i <= 4; i++) sum += i;
  • 27. initialize i = 1 test 1 <= 4 is true execute body sum += 1 (result: sum = 0 + 1 = 1) update i++ (result: i = 2) test 2 <= 4 is true execute body sum += 2 (result: sum = 1 + 2 = 3) update i++ (result: i = 3) test 3 <= 4 is true execute body sum += 3 (result: sum = 3 + 3 = 6) update i++ (result: i + 4) test 4 <= 4 is true execute body sum += 4 (result: sum = 6 + 4 = 10) update i++ (result: i = 5) test 5 <= 4 is false Figure 4.18 Trace of execution of the for loop of Figure 4.17
  • 28. Figure 4.19 A for statement for the sum 1+3+5+7+9 int sum = 0; for (int i = 1; i < 10; i += 2) sum += i;
  • 29. Figure 4.20 A for statement for the sum 4+3+2+1 int sum = 0; for (int i = 4; i >= l; i--) sum += i;
  • 30. Figure 4.21 Declaring an index variable before the for loop int i; // declare loop index int sum = 0; for (i = 4; i >= 1; i--) // initialize loop index sum += i; ... i += 17; // use variable i
  • 31. Examples • TwelveDays.java (extra) • Diamond.java (extra) • Growth.java • Mortgage.java (extra)
  • 32. The StringTokenizer Class • StringTokenizer(String str) Constructor. Creates a new StringTokenizer object to parse str based on white space • StringTokenizer(String str, String delimiter) Constructor. Creates a new StringTokenizer object to parse str based on specified set of delimiteds • int countTokens() Returns the number of token still left to be processed in the string • boolean hasMoreTokens() Returns true if there are tokens still left to be processed in the string • String nextToken() Returns the next token in the string
  • 33. Figure 4.22 Syntax for the do-while statement do statement while (condition) ;
  • 34. Do-while Statement • A do-while statement checks the condition after executing the loop body • The loop body of a do-while statement is executed at least once • Do-while statements are suitable for writing loops that are executed at least once • DoGrowth.java • Babylonian.java (extra)
  • 35. Figure 4.23 Pseudocode for example 4.5 enhancement do { Compute balance as in Example 4.5 Ask the user -- Repeat or Quit? } while (User chooses to repeat);
  • 36. The char Type • Java uses Unicode charater set (16 bits) • ASCII, American Standard Code for Information Interchange, is a seven-bit code used by other language like C and C++ • ASCII is a subset of Unicode • Keyword char to denote character type • Character constants are quoted in single quotes, e.g. ‘A’ • Ascii.java
  • 37. Escape Sequence • Escape sequence: preceding certain character with the escape character for special meaning • The newline, 'n', positions the next output at the start of the next line • The return, 'r', positions the next output at the start of the curent line • The backspace, 'b', positions the next output one character to the left • The tab, 't', position the next output at the next tab position
  • 38. Escape Sequence • The escape needs to be "escaped" when quoted like '' and "" • The single quote character must be "escaped" in single quotes like ''' • The double quote must be "escaped" in double quotes like ””This is a quote”" • Special.java
  • 39. backlash Special Character Meaning n newline, move to the start of the next line t tab b backspace r return, move to the start of the current line " double quote n newline, move to the start of the next line Figure 4.24 Escape sequences for special characters
  • 40. The byte, short, and long Types • byte: one byte = 8 bits, range from -128 to 127 • short: two bytes = 16 bits – range from -32,768 to 32,767 • int: four bytes = 32 bits – range from -2,147,483,648 to 2,147,483,647 • long: eight bytes = 64 bits – range 9,223,372,036,854,808 to 9,223,372,036,854,807 • int is the default for integer constant • Integer constants can be made long by adding the suffix l or L
  • 41. The float Type • float: four bytes = 32 bits – Exponent can range from -45 to 48 – Min ~ -3.4E+38 with seven significant digits – Max ~ 3.4E+38 with seven significant digits • double: eight bytes = 64 bits – Exponent can range from -324 to 308 – Min ~ -1.7E+308 with 16 significant digits – Max ~ 1.7E+308 with 16 significant digits • double is the default for real constants • Make a number float by adding an f or F suffix float good = 4.25f; // valid float ok = (float)4.25; // valid float bad = 4.25; // invalid
  • 42. The Math Class • In java.lang package • Two static constants: E (base of natural log) and PI (ratio of circumference of a circle to its diameter) • General functions abs - absolute value ceil - ceiling, smallest integer >= argument floor - flooring, greatest integer <= argument round - rounding, integer closest to argument max - maximum of the two arguments min - minimum of the two arguments
  • 43. The Math Class • Simple mathematical operations sqrt(double a) - Return the square root of the argument pow(double a, double b) - Returns of value of the first argument raised to the power of the second argument log(double a) - Returns the natural logarithm (base e) of a double value exp(double a) - Returns the exponential number e (i.e., 2.718...) raised to the power of a double value • Random number random() - Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0
  • 44. The Math Class • Trigonometric functions sin, cos, tan - sine, cosine, and tangent asin, acos, atan- arc-sine, arc-cosine, and arc-tangent atan2(double a, double b) - Returns the theta component in the polar coordinates (r, theta) corresponding to the point (b, a) in Cartesian coordinates • Degree/Radian conversion toDegrees(double angrad) - Converts an angle in radians to the equivalent angle measured in degrees toRadians(double angdeg) - Converts an angle in degrees to the equivalent angle measured in radians
  • 45. The Math Class • Library.java • Toss.java • CoinToss.java
  • 46. Figure 4.25 Size of the reward given each day 1 1 2 4 8 12 16 16 8 4 2 Days
  • 47. Figure 4.26 Using random numbers to represent heads and tails 0.0 0.5 1.0 HHHHHHHHHHHHHHHHHTTTTTTTTTTTTTTTTTT Heads Tails
  • 48. Iterative Development Cycle • First iteration - CovertMenu.java (with stubs for methods) • Second iteration - CovertFromMetric.java (implement MetricToEnglish()) • Third iteration - Convert.java (implement EnglishToMetric())
  • 49. Figure 4.27 Iterative problem-solving process Formulate the problem; do { Develop pseudocode; Implement pseudocode in Java program; Test program; while (More subproblems to refine);
  • 50. Figure 4.28 Top-level Pseudocode do [ Display the menu; Get the user's choice; Execute the user's choice; } while (user does not choose to quit);
  • 51. Figure 4.29 Pattern for a menu-driven application do { System.out.println(); System.out.println("Choose from the following list"); System.out.println("1. Convert from meters to yds,ft,in"); System.out,println("2. Convert from yds,ft,in to meters"); System.out.println("3. Quit"); int choice = Io.readInt("Enter your choice, 1, 2 or 3"); switch (choice) { case 1: MetricToEnglish(); break; case 2: EnglishToMetric(); break; case 3: System.out.println("Bye, Have a nice day"); } } while (choice != 3);
  • 52. Figure 4.30 Pseudocode for the MetricToEnglish method Input the number of meters, x, to convert; Convert x meters to y yards; Separate y into yInteger yards and yFraction yards; Convert yFraction yards to f feet. Separate f into fInteger feet and fFraction feet. Convert fFraction feet to i inches. Display the output.
  • 53. Figure 4.31 Refinement:Display the output if (yInteger > 0) if (yInteger <= 1) Display yInteger yard; else Display yInteger yards; if (fInteger > 0) if (fInteger <= 1) Display fInteger foot; else Display fInteger feet; if (i >0) if (i <= 1) Display i inch; else Display i inches; if (yInteger == 0 && fInteger == 0 && i == 0) Display 0 yards;
  • 54. Figure 4.32 Pseudocode for the EnglishToMetric method Input yards, feet, and inches to convert; Convert to inches; Convert inches to meters; Output the result;