SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Chapter 4: Control
Structures I
JAVA PROGRAMMING:
FROM PROBLEM ANALYSIS TO PROGRAM DESIGN,
SECOND EDITION
2
Chapter Objectives
 Learn about control structures.
 Examine relational and logical operators.
 Explore how to form and evaluate logical
(Boolean) expressions.
 Learn how to use the selection control
structures if, if…else, and switch in
a program.
3
Control Structures
 Three methods of processing a program:
 In sequence
 Branching
 Looping
 Branch: Altering the flow of program
execution by making a selection or choice.
 Loop: Altering the flow of program
execution by repeating statements.
4
Control Structures
5
Relational Operators
 Relational operator:
 Allows you to make comparisons in a program.
 Binary operator.
 Condition is represented by a logical
expression in Java.
 Logical expression: An expression that has
a value of either true or false.
6
Relational Operators
7
Relational Operators and
Primitive Data Types
 Can be used with integral and floating-point
data types.
 Can be used with the char data type.
 Unicode Collating Sequence.
8
Relational Operators and Primitive Data Types
9
Comparing Strings
 class String
 Method compareTo
 Method equals
 Given string str1 and str2





=
>>
<<
str2str10
str2str10
str2str10
reTo(str2)str1.compa
stringifintegeran
stringtoequalisstringif
stringifintegeran
10
Comparing Strings
String str1 = "Hello";
String str2 = "Hi";
String str3 = "Air";
String str4 = "Bill";
String str5 = "Bigger";
11
Comparing Strings
12
Comparing Strings
13
Comparing Strings
14
Comparing Strings
15
Short-Circuit Evaluation
 A process in which the computer evaluates
a logical expression from left to right and
stops as soon as the value of the expression
is known.
16
Selection
 One-way selection
 Two-way selection
 Compound (block of) statements
 Multiple selections (nested if)
 Conditional operator
 switch structures
17
One-Way Selection
 Syntax:
if (expression)
statement
 Expression referred to as decision maker.
 Statement referred to as action statement.
18
Example 4-11
//Determine the absolute value of an integer
import javax.swing.JOptionPane;
public class AbsoluteValue
{
public static void main(String[] args)
{
int number;
int temp;
String numString;
numString =
JOptionPane.showInputDialog
("Enter an integer:"); //Line 1
number = Integer.parseInt(numString); //Line 2
temp = number; //Line 3
One-Way Selection
19
if (number < 0) //Line 4
number = -number; //Line 5
JOptionPane.showMessageDialog(null,
"The absolute value of " + temp
+ " is " + number,
"Absolute Value",
JOptionPane.INFORMATION_MESSAGE); //Line 6
System.exit(0);
}
One-Way Selection
20
Two-Way Selection
 Syntax:
if (expression)
statement1
else
statement2
 else statement must be paired with an if.
21
Two-Way Selection
22
Two-Way Selection
Example 4-14
if (hours > 40.0)
wages = 40.0 * rate +
1.5 * rate * (hours - 40.0);
else
wages = hours * rate;
23
Example 4-15
if (hours > 40.0); //Line 1
wages = 40.0 * rate +
1.5 * rate * (hours - 40.0); //Line 2
else //Line 3
wages = hours * rate; //Line 4
Because a semicolon follows the closing parenthesis of the if
statement (Line 1), the else statement stands alone. The
semicolon at the end of the if statement (see Line 1) ends the
if statement, so the statement at Line 2 separates the else
clause from the if statement. That is, else is by itself.
Because there is no separate else statement in Java, this code
generates a syntax error.
Two-Way Selection
24
Compound (Block of) Statements
Syntax:
{
statement1
statement2
.
.
.
statementn
}
25
Compound (Block of) Statements
if (age > 18)
{
System.out.println("Eligible to vote.");
System.out.println("No longer a minor.");
}
else
{
System.out.println("Not eligible to vote.");
System.out.println("Still a minor.");
}
26
Multiple Selection: Nested if
 Syntax:
if (expression1)
statement1
else
if (expression2)
statement2
else
statement3
 Else is associated with the
most recent incomplete if.
 Multiple if statements can
be used in place of if…
else statements.
 May take longer to
evaluate.
27
Conditional (? :) Operator
 Ternary operator
 Syntax:
expression1 ? expression2 :
expression3
 If expression1 = true, then the result of the
condition is expression2.
Otherwise, the result of the condition is
expression3.
28
switch Structures
 Expression is also
known as selector.
 Expression can be an
identifier.
 Value can only be
integral.
switch (expression)
{
case value1: statements1
break;
case value2: statements2
break;
...
case valuen: statementsn
break;
default: statements
}
29
switch Structures
30
Example 4-24
switch (grade)
{
case 'A': System.out.println("The grade is A.");
break;
case 'B': System.out.println("The grade is B.");
break;
case 'C': System.out.println("The grade is C.");
break;
case 'D': System.out.println("The grade is D.");
break;
case 'F': System.out.println("The grade is F.");
break;
default: System.out.println("The grade is
invalid.");
}
switch Structures
31
Programming Example:
Cable Company Billing
 Input: Customer’s account number,
customer code, number of premium
channels to which customer subscribes,
number of basic service connections (in the
case of business customers).
 Output: Customer’s account number and the
billing amount.
32
Programming Example:
Cable Company Billing
Solution:
1. Prompt user for information.
2. Use switch statements based on customer’s
type.
3. Use an if statement nested within a switch
statement to determine the amount due by
each customer.
33
Chapter Summary
 Control structures are used to process programs.
 Logical expressions and order of precedence of
operators are used in expressions.
 Compare strings.
 If statements.
 if…else statements.
 switch structures.
 Proper syntax for using control statements.

Weitere ähnliche Inhalte

Was ist angesagt?

Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
Ravi_Kant_Sahu
 

Was ist angesagt? (20)

Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
String in java
String in javaString in java
String in java
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Primitive data types in java
Primitive data types in javaPrimitive data types in java
Primitive data types in java
 
Strings
StringsStrings
Strings
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Java string handling
Java string handlingJava string handling
Java string handling
 
String in programming language in c or c++
 String in programming language  in c or c++  String in programming language  in c or c++
String in programming language in c or c++
 
Stacks
StacksStacks
Stacks
 
Decision Making Statement in C ppt
Decision Making Statement in C pptDecision Making Statement in C ppt
Decision Making Statement in C ppt
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Operators in java
Operators in javaOperators in java
Operators in java
 
C++ string
C++ stringC++ string
C++ string
 
datatypes and variables in c language
 datatypes and variables in c language datatypes and variables in c language
datatypes and variables in c language
 

Andere mochten auch

Control statements in Java
Control statements  in JavaControl statements  in Java
Control statements in Java
Jin Castor
 
Control Structures
Control StructuresControl Structures
Control Structures
Ghaffar Khan
 

Andere mochten auch (20)

Control statements
Control statementsControl statements
Control statements
 
Control statements in Java
Control statements  in JavaControl statements  in Java
Control statements in Java
 
Control Structures
Control StructuresControl Structures
Control Structures
 
Flowchart Diagram Templates by Creately
Flowchart Diagram Templates by CreatelyFlowchart Diagram Templates by Creately
Flowchart Diagram Templates by Creately
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
 
Principle of marketing
Principle of marketing Principle of marketing
Principle of marketing
 
Python in Computer Vision
Python in Computer VisionPython in Computer Vision
Python in Computer Vision
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
Effective writing, tips for Bloggers
Effective writing, tips for BloggersEffective writing, tips for Bloggers
Effective writing, tips for Bloggers
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
What is business
What is businessWhat is business
What is business
 
System outputs - Computer System
System outputs - Computer SystemSystem outputs - Computer System
System outputs - Computer System
 
Basic characteristics of business
Basic characteristics of businessBasic characteristics of business
Basic characteristics of business
 
What is computer Introduction to Computing
What is computer Introduction  to Computing What is computer Introduction  to Computing
What is computer Introduction to Computing
 
Strategic planning and mission statement
Strategic planning and mission statement Strategic planning and mission statement
Strategic planning and mission statement
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 

Ähnlich wie Control structures i

Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 

Ähnlich wie Control structures i (20)

Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfBasic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
Ch05.pdf
Ch05.pdfCh05.pdf
Ch05.pdf
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Ch04
Ch04Ch04
Ch04
 
Java input Scanner
Java input Scanner Java input Scanner
Java input Scanner
 
Ch05-converted.pptx
Ch05-converted.pptxCh05-converted.pptx
Ch05-converted.pptx
 
03a control structures
03a   control structures03a   control structures
03a control structures
 
Operators
OperatorsOperators
Operators
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)
 
PE1 Module 3.ppt
PE1 Module 3.pptPE1 Module 3.ppt
PE1 Module 3.ppt
 
C# language basics (Visual Studio)
C# language basics (Visual Studio) C# language basics (Visual Studio)
C# language basics (Visual Studio)
 
C# language basics (Visual studio)
C# language basics (Visual studio)C# language basics (Visual studio)
C# language basics (Visual studio)
 
slides03.ppt
slides03.pptslides03.ppt
slides03.ppt
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Chapter 2 - Flow of Control Part I.pdf
Chapter 2 -  Flow of Control Part I.pdfChapter 2 -  Flow of Control Part I.pdf
Chapter 2 - Flow of Control Part I.pdf
 
Control statments in c
Control statments in cControl statments in c
Control statments in c
 

Mehr von Ahmad Idrees

An overview of computers and programming languages
An overview of computers and programming languages An overview of computers and programming languages
An overview of computers and programming languages
Ahmad Idrees
 

Mehr von Ahmad Idrees (8)

An overview of computers and programming languages
An overview of computers and programming languages An overview of computers and programming languages
An overview of computers and programming languages
 
Marketing research links consumer
Marketing research links consumer Marketing research links consumer
Marketing research links consumer
 
Marketing mix and 4 p's
Marketing mix and 4 p's Marketing mix and 4 p's
Marketing mix and 4 p's
 
Managing marketing information
Managing marketing information Managing marketing information
Managing marketing information
 
Swot analysis Marketing Principle
Swot analysis Marketing Principle Swot analysis Marketing Principle
Swot analysis Marketing Principle
 
C++ programming program design including data structures
C++ programming program design including data structures C++ programming program design including data structures
C++ programming program design including data structures
 
Basic qualities of a good businessman
Basic qualities of a good businessmanBasic qualities of a good businessman
Basic qualities of a good businessman
 
Top 40 seo myths everyone should know about
Top 40 seo myths everyone should know aboutTop 40 seo myths everyone should know about
Top 40 seo myths everyone should know about
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 

Control structures i

  • 1. Chapter 4: Control Structures I JAVA PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM DESIGN, SECOND EDITION
  • 2. 2 Chapter Objectives  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate logical (Boolean) expressions.  Learn how to use the selection control structures if, if…else, and switch in a program.
  • 3. 3 Control Structures  Three methods of processing a program:  In sequence  Branching  Looping  Branch: Altering the flow of program execution by making a selection or choice.  Loop: Altering the flow of program execution by repeating statements.
  • 5. 5 Relational Operators  Relational operator:  Allows you to make comparisons in a program.  Binary operator.  Condition is represented by a logical expression in Java.  Logical expression: An expression that has a value of either true or false.
  • 7. 7 Relational Operators and Primitive Data Types  Can be used with integral and floating-point data types.  Can be used with the char data type.  Unicode Collating Sequence.
  • 8. 8 Relational Operators and Primitive Data Types
  • 9. 9 Comparing Strings  class String  Method compareTo  Method equals  Given string str1 and str2      = >> << str2str10 str2str10 str2str10 reTo(str2)str1.compa stringifintegeran stringtoequalisstringif stringifintegeran
  • 10. 10 Comparing Strings String str1 = "Hello"; String str2 = "Hi"; String str3 = "Air"; String str4 = "Bill"; String str5 = "Bigger";
  • 15. 15 Short-Circuit Evaluation  A process in which the computer evaluates a logical expression from left to right and stops as soon as the value of the expression is known.
  • 16. 16 Selection  One-way selection  Two-way selection  Compound (block of) statements  Multiple selections (nested if)  Conditional operator  switch structures
  • 17. 17 One-Way Selection  Syntax: if (expression) statement  Expression referred to as decision maker.  Statement referred to as action statement.
  • 18. 18 Example 4-11 //Determine the absolute value of an integer import javax.swing.JOptionPane; public class AbsoluteValue { public static void main(String[] args) { int number; int temp; String numString; numString = JOptionPane.showInputDialog ("Enter an integer:"); //Line 1 number = Integer.parseInt(numString); //Line 2 temp = number; //Line 3 One-Way Selection
  • 19. 19 if (number < 0) //Line 4 number = -number; //Line 5 JOptionPane.showMessageDialog(null, "The absolute value of " + temp + " is " + number, "Absolute Value", JOptionPane.INFORMATION_MESSAGE); //Line 6 System.exit(0); } One-Way Selection
  • 20. 20 Two-Way Selection  Syntax: if (expression) statement1 else statement2  else statement must be paired with an if.
  • 22. 22 Two-Way Selection Example 4-14 if (hours > 40.0) wages = 40.0 * rate + 1.5 * rate * (hours - 40.0); else wages = hours * rate;
  • 23. 23 Example 4-15 if (hours > 40.0); //Line 1 wages = 40.0 * rate + 1.5 * rate * (hours - 40.0); //Line 2 else //Line 3 wages = hours * rate; //Line 4 Because a semicolon follows the closing parenthesis of the if statement (Line 1), the else statement stands alone. The semicolon at the end of the if statement (see Line 1) ends the if statement, so the statement at Line 2 separates the else clause from the if statement. That is, else is by itself. Because there is no separate else statement in Java, this code generates a syntax error. Two-Way Selection
  • 24. 24 Compound (Block of) Statements Syntax: { statement1 statement2 . . . statementn }
  • 25. 25 Compound (Block of) Statements if (age > 18) { System.out.println("Eligible to vote."); System.out.println("No longer a minor."); } else { System.out.println("Not eligible to vote."); System.out.println("Still a minor."); }
  • 26. 26 Multiple Selection: Nested if  Syntax: if (expression1) statement1 else if (expression2) statement2 else statement3  Else is associated with the most recent incomplete if.  Multiple if statements can be used in place of if… else statements.  May take longer to evaluate.
  • 27. 27 Conditional (? :) Operator  Ternary operator  Syntax: expression1 ? expression2 : expression3  If expression1 = true, then the result of the condition is expression2. Otherwise, the result of the condition is expression3.
  • 28. 28 switch Structures  Expression is also known as selector.  Expression can be an identifier.  Value can only be integral. switch (expression) { case value1: statements1 break; case value2: statements2 break; ... case valuen: statementsn break; default: statements }
  • 30. 30 Example 4-24 switch (grade) { case 'A': System.out.println("The grade is A."); break; case 'B': System.out.println("The grade is B."); break; case 'C': System.out.println("The grade is C."); break; case 'D': System.out.println("The grade is D."); break; case 'F': System.out.println("The grade is F."); break; default: System.out.println("The grade is invalid."); } switch Structures
  • 31. 31 Programming Example: Cable Company Billing  Input: Customer’s account number, customer code, number of premium channels to which customer subscribes, number of basic service connections (in the case of business customers).  Output: Customer’s account number and the billing amount.
  • 32. 32 Programming Example: Cable Company Billing Solution: 1. Prompt user for information. 2. Use switch statements based on customer’s type. 3. Use an if statement nested within a switch statement to determine the amount due by each customer.
  • 33. 33 Chapter Summary  Control structures are used to process programs.  Logical expressions and order of precedence of operators are used in expressions.  Compare strings.  If statements.  if…else statements.  switch structures.  Proper syntax for using control statements.