Chapter 4: Control Structures I - PowerPoint PPT Presentation

1 / 41
About This Presentation
Title:

Chapter 4: Control Structures I

Description:

Allows you to make comparisons in a program. Binary operator. ... Method abs for comparing equality of floating number. E.g. Math.abs(x-y) 0.0000000001 ... – PowerPoint PPT presentation

Number of Views:47
Avg rating:3.0/5.0
Slides: 42
Provided by: manasi61
Category:

less

Transcript and Presenter's Notes

Title: Chapter 4: Control Structures I


1
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, ifelse, 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.
  • Method abs for comparing equality of floating
    number
  • E.g. Math.abs(x-y) lt 0.0000000001

8
Relational Operators and Primitive Data Types
9
Comparing Strings
  • class String
  • Method compareTo
  • Method equals
  • Given string str1 and str2

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.
  • Caution avoid expressions such as 0ltnumlt10
    (syntax error)
  • Use 0ltnum num lt 10

16
  • import java.util.
  • public class contrstruc
  • public static void main(String args)
  • float faith
  • double faith1
  • double ans
  • faith 2
  • faith1 (4.0/1.999991)
  • ans Math.abs(faith-faith1)
  • System.out.println(ans)
  • // to compare string values
  • int ans1
  • int ans2
  • String fa
  • String fa1
  • fa "Sun"

17
  • // To use the method equals to compare two
    strings
  • boolean ans3
  • String fa3 "Fathe"
  • String fa4
  • fa4 "fathe"
  • ans3 fa3.equals(fa4)
  • System.out.println(ans3)
  • // Logical Operators
  • boolean ans6, ans4, ans5
  • ans6 !('A'gt'B')
  • ans4 !('A'gt'B') (126)
  • ans5 !('A'gt'B') ('N'lt'M')
  • System.out.println(ans6 " " ans4 " "
    ans5)
  • // logical expression
  • boolean ans7
  • ans7 11gt5 (6lt15 7gt8)
  • System.out.println(ans7)

18
Selection
  • One-way selection
  • Two-way selection
  • Compound (block of) statements
  • Multiple selections (nested if)
  • Conditional operator
  • switch structures

19
One-Way Selection
  • Syntax
  • if (expression)
  • statement
  • Expression referred to as decision maker.
  • Statement referred to as action statement.

20
  • import java.util.
  • public class contrstucif
  • public static void main(String args)
  • // one way selection -if(expression)statement
  • int x
  • char y
  • String ans
  • x 9
  • y 'k'
  • if(xgty)ans"Yes"

21
  • mport java.util.
  • import javax.swing.JOptionPane
  • public class controlif
  • public static void main(String args)
  • // to determine absolute value of an
    integer.
  • int num
  • int temp
  • String numstr
  • numstrJOptionPane.showInputDialog("Enter and
    Integer Number") // the number to look for its
    absolute value
  • num Integer.parseInt(numstr) // converts the
    value of the numstr into integer
  • temp num
  • if(numlt0)num-num // there must be parenthesis
    around the logical expression
  • JOptionPane.showMessageDialog(null, "The absolute
    value of " temp "is" num, "Abs value",
    JOptionPane.INFORMATION_MESSAGE)
  • System.exit(0)

22
Two-Way Selection
  • Syntax
  • if (expression)
  • statement1
  • else
  • statement2
  • else statement must be paired with an if.

23
Two-Way Selection
24
Two-Way Selection
Example 4-14 if (hours gt 40.0) wages 40.0
rate 1.5 rate (hours -
40.0) else wages hours rate
25
Two-Way Selection
Example 4-15 if (hours gt 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.
26
  • // two way selection if ...else (no
    'then')
  • int rate
  • double salary
  • double hours
  • String hourstr
  • hourstr JOptionPane.showInputDialog("Enter hours
    worked")
  • hoursDouble.parseDouble(hourstr)
  • if(hourslt60)
  • salary45hours
  • else
  • salary40hours22
  • System.out.println()
  • System.out.println(salary)
  • System.exit(0)

27
Compound (Block of) Statements
  • Syntax
  • statement1
  • statement2
  • .
  • .
  • .
  • statementn

28
Compound (Block of) Statements
  • if (age gt 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.")

29
  • // Compound Statements
  • String agestr
  • float age
  • //agestrJOptionPane.showInputDialog("Enter
    Age")
  • //ageFloat.parseFloat(agestr)
  • age20
  • if(agegt18)
  • System.out.println("Eligible to vate")
  • System.out.println("Not a minor")
  • else
  • System.out.println("Not eligible to vote")
  • System.out.println("Still a minor")

30
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
    ifelse statements.
  • May take longer to evaluate.

31
  • // Nested if statements
  • double balance
  • String balstr
  • Double interest
  • balstr JOptionPane.showInputDialog("Enter
    balance")
  • balanceDouble.parseDouble(balstr)
  • if(balancegt500)
  • interest0.05
  • else
  • if(balancegt250)
  • interest0.04
  • else
  • if(balancegt100)
  • interest0.03
  • else
  • interest0.05
  • System.out.println(interest)
  • System.exit(0)

32
  • import javax.swing.
  • import java.util.
  • public class controlif1
  • public static void main(String args)
  • String monthstr
  • int month
  • monthstrJOptionPane.showInputDialog("Enter an
    integer for month")
  • monthInteger.parseInt(monthstr)
  • if(month1)
  • System.out.println("January")
  • else if(month2)
  • System.out.println("February")
  • else if(month3)
  • System.out.println("March")
  • else if(month4)
  • System.out.println("April")
  • System.exit(0)

33
  • // Another Format without else
  • monthstrJOptionPane.showInputDialog("Enter an
    integer for month")
  • monthInteger.parseInt(monthstr)
  • if(month1)
  • System.out.println("January")
  • if(month2)
  • System.out.println("February")
  • if(month3)
  • System.out.println("March")
  • if(month4)
  • System.out.println("April")

34
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.

35
  • //Use of conditional operator ?
  • int faith, faith1
  • String faithstr, faith1str
  • int owner
  • faithstrJOptionPane.showInputDialog("Enter the
    value for Faith")
  • faithInteger.parseInt(faithstr)
  • faith1strJOptionPane.showInputDialog("Enter the
    value for Faith1")
  • faith1Integer.parseInt(faith1str)
  • if(faithgtfaith1)
  • owner faith
  • else
  • ownerfaith1
  • System.out.println(owner)
  • //Alternative way of writing this using the ?
    operator
  • owner(faithgtfaith1)? faithfaith1
  • System.out.println(owner)

36
switch Structures
switch (expression) case value1 statements1
break case value2 statements2
break ... case valuen statementsn
break default statements
  • Expression is also known as selector.
  • Expression can be an identifier.
  • Value can only be integral.

37
switch Structures
38
  • import java.util.
  • public class controlif2
  • static Scanner console new Scanner(System.in)
  • public static void main(String args)
  • char grade
  • System.out.println("Please enter the letter
    grade")
  • gradeconsole.next().charAt(0)
  • System.out.println()
  • switch (grade)
  • case 'A' System.out.println("The Grade is A")
  • break
  • case 'B' System.out.println("The Grade is B")

39
Programming Example Cable Company Billing
  • Input Customers account number, customer code,
    number of premium channels to which customer
    subscribes, number of basic service connections
    (in the case of business customers).
  • Output Customers account number and the billing
    amount.

40
Programming Example Cable Company Billing
  • Solution
  • Prompt user for information.
  • Use switch statements based on customers type.
  • Use an if statement nested within a switch
    statement to determine the amount due by each
    customer.

41
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.
  • ifelse statements.
  • switch structures.
  • Proper syntax for using control statements.
Write a Comment
User Comments (0)
About PowerShow.com