if Statement - PowerPoint PPT Presentation

About This Presentation
Title:

if Statement

Description:

if Statement if (amount – PowerPoint PPT presentation

Number of Views:175
Avg rating:3.0/5.0
Slides: 40
Provided by: Facu208
Category:

less

Transcript and Presenter's Notes

Title: if Statement


1
if Statement
  • if (amount lt balance)
  • balance balance - amount

2
if/else Statement
  • if (amount lt balance) balance balance -
    amount
  • else balance balanceOVERDRAFT_PENALTY

3
Block Statement
  • if (amount lt balance)
  • double newBalance balance - amount
    balance newBalance
  • Note block allows more than one statement
  • to be combined, to form a new statement

4
Equality Testing vs. Assignment
  • The operator tests for equalityif (x 0)
    . . // if x equals zero
  • The operator assigns a value to a variablex
    0 // assign 0 to x
  • Don't confuse them.
  • Java is the same as mathematical

5
Comparing Floating-Point Numbers
  • Consider this code
  • double r Math.sqrt(2) double d r r -2
    if (d 0) System.out.println(
    "sqrt(2)squared minus 2 is 0") else
    System.out.println( "sqrt(2)squared minus 2
    is not 0 but " d)

6
  • It printssqrt(2)squared minus 2 is not 0 but
    4.440892098500626E-16
  • Don't use to compare floating-point numbers

7
Comparing Floating-Point Numbers
  • Two numbers are close to another if x - y lt e
  • e is a small number such as 10-14
  • Not good enough if x, y very large or very small.
    Then usex - y / max(x, y) lt e
  • But if one of the numbers is zero, don't divide
    by max(x , y)

8
String Comparison
  • Don't use for strings!if (input "Y") //
    WRONG!!!
  • Use equals methodif (input.equals("Y"))
  • tests identity, equals tests equal contents
  • Case insensitive test ("Y" or "y")if
    (input.equalsIgnoreCase("Y"))

9
Lexicographic Comparison
  • s.compareTo(t) lt 0 means s comes before t in
    the dictionary
  • "car"comes before "cargo" "cargo" comes before
    "cathode"
  • All uppercase letters come before lowercase
    "Hello" comes before "car"

10
Lexicographic Comparison
11
Object Comparison
  • tests for identical object
  • equals for identical object content
  • Rectangle cerealBox new
    Rectangle(5, 10, 20, 30)Rectangle oatmealBox
    new Rectangle(5, 10, 20,
    30)Rectangle r cerealBox
  • cerealBox ! oatmealBox, but
    cerealBox.equals(oatmealBox)
  • cerealBox r
  • Caveat equals must be defined for the
    class (chap 11)

12
Object Comparison
13
The null Reference
  • null reference refers to no object at all
  • Can be used in tests if (account null)
    . . .
  • Use , not equals, to test for null
  • showInputDialog returns null if the user hit the
    cancel buttonString input JOptionPane.showInpu
    tDialog("...")if (input ! null) ...
  • null is not the same as the empty string ""

14
Multiple Alternatives
  • if (condition1) statement1else if
    (condition2) statement2else if
    (condition3) statement3else
    statement4
  • The first matching condition is executed.
  • Order matters.

15
Multiple Alternatives
  • Order matters
  • if (condition1)
  • Statement1
  • else if (condition2)
  • Statement2
  • else if (condition3)
  • Statement3
  • else // option executes of all conditions
    fail
  • Statement4

16
Nested Branches
  • Branch inside another branch
  • if (condition1) if (condition1a)
    statement1a else statement1belse
    statement2

17
The boolean Type
  • George Boole (1815-1864) pioneer in the study of
    logic
  • value of expression amount lt 1000 is true or
    false.
  • boolean type set of 2 values, true and false

18
Predicate Method
  • return type boolean
  • Examplepublic boolean isOverdrawn() return
    balance lt 0
  • Use in conditionsif (harrysChecking.isOverdrawn()
    ) ...
  • Useful predicate methods in Character
    classisDigitisLetterisUpperCaseisLowerCase
  • if (Character.isUpperCase(ch)) ...

19
Boolean Operators
  • ! not
  • and (short circuited)
  • or (short circuited)

20
Truth Tables
21
Boolean Variables
  • private boolean married
  • Set to truth valuemarried input.equals("M")
  • Use in conditionsif (married) ... else ...if
    (!married) ...
  • Also called flag
  • Don't test Boolean variables against truth
    values--sign of cluelessnessif (married
    true) // DON'Tif (married false) // DON'Tif
    (married ! false) // NO!!!

22
Investment with Compound Interest
Invest 10,000, 5 interest, compounded annually
When will the balance be at least 20,000?
23
while Statement
  • while (condition) statement//repeats
    the statement while the condition is truewhile
    (balance lt targetBalance) year double
    interest balance rate / 100 balance
    balance interest

24
Flowchart for while Loop
25
Common Error Infinite Loop
  • while (year lt 20)
  • balance balance balance rate / 100
  • while (year gt 0)
  • year // oops, meant --
  • Loops run forever--must kill program

26
Common Error Off-by-1 Error
  • year 0while (balance lt targetBalance)
  • year double interest balance
    rate / 100 balance balance interest
    System.out.println("Reached target after "
    year " years.")
  • Should year start at 0 or 1?
  • Should the test be lt or lt?

27
Avoiding Off-by-1 Error
  • Run through a simple exampletarget balance
    20,000, interest rate 50after one year
    balance 15,000after two years balance
    22,500Therefore year must start at 0
  • interest rate 100after one year balance
    20,000loop should stopTherefore must use lt
  • Think, don't compile and try at random

28
do Statement
  • Executes loop body at least once
  • do statement
  • while (condition)
  • Example Validate input
  • double valuedo String input
    JOptionPane.showInputDialog( "Please enter
    a positive number") value
    Integer.parseInt(input) while (input lt 0)

29
Flowchart for do Loop
30

for Statement
  • for (initialization condition update)
    statement
  • Example for (int i 1 i lt n i) double
    interest balance rate / 100 balance
    balance interest
  • Equivalent to
  • initialization
  • while (condition)
  • statement
  • update

31
Flowchart for for Loop
32
Common Errors Semicolons
  • A semicolon that shouldn't be there
  • sum 0for (i 1 i lt 10 i) sum
    sum iSystem.out.println(sum)

33
Common Errors Semicolons
  • A semicolon that shouldn't be there
  • sum 0 i 1
  • while ( i lt 10)
  • sum sum i
  • i i 1
  • System.out.println(sum)

34
Nested Loops
  • Create triangle pattern
  • Loop through rowsfor (int i 1 i lt n i)
    // make triangle row

35
  • Make triangle row is another loop
  • for (int j 1 j lt i j) r r ""r
    r "\n"
  • Put loops together gt Nested loops
  • for (int i 1 i lt width i)
  • // make triangle row
  • for (int j 1 j lt i j)
  • r r ""
  • r r "\n"

36
Reading Input Values
  • General pattern
  • boolean done falsewhile (!done) String
    input read input if (end of input
    indicated) done true else
    process input
  • "Loop and a half"

37
Another option
  • General pattern
  • while (end of input ! read input )
    process input

38
String Tokenization
  • StringTokenizer breaks up string into tokens
  • By default, white space separates tokens
  • "4.3 7 -2" breaks into three tokens"4.3", "7",
    "-2"
  • StringTokenizer tokenizer new
    StringTokenizer(a String)while
    (tokenizer.hasMoreTokens()) String token
    tokenizer.nextToken() process token

39
Traversing Characters in String
  • s.charAt(i) is the ith character of the string s
  • for (int i 0 i lt s.length() i) char ch
    s.charAt(i) process ch
Write a Comment
User Comments (0)
About PowerShow.com