Download presentation
Presentation is loading. Please wait.
Published bySharon Payne Modified over 9 years ago
1
if Statement if (amount <= balance) balance = balance - amount;
2
if/else Statement if (amount <= balance) balance = balance - amount; else balance = balanceOVERDRAFT_PENALTY;
3
Block Statement if (amount <= 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 equality: if (x = = 0).. // if x equals zero The = operator assigns a value to a variable: x = 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 prints: sqrt(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| <= ε ε is a small number such as 10 -14 Not good enough if x, y very large or very small. Then use |x - y| / max(|x|, |y|) <= ε 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 method: if (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) < 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 button: String input = JOptionPane.showInputDialog("..."); if (input != null) {... } null is not the same as the empty string ""
14
Multiple Alternatives if (condition1) statement1; else if (condition2) statement2; else if (condition3) statement3; else 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 statement1b; } else statement2;
17
The boolean Type George Boole (1815-1864): pioneer in the study of logic value of expression amount < 1000 is true or false. boolean type: set of 2 values, true and false
18
Predicate Method return type boolean Example: public boolean isOverdrawn() { return balance < 0; } Use in conditions if (harrysChecking.isOverdrawn())... Useful predicate methods in Character class: isDigit isLetter isUpperCase isLowerCase 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 value: married = input.equals("M"); Use in conditions: if (married)... else... if (!married)... Also called flag Don't test Boolean variables against truth values-- sign of cluelessness: if (married == true) // DON'T if (married == false) // DON'T if (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 true while (balance < targetBalance){ year++; double interest = balance * rate / 100; balance = balance + interest; }
24
Flowchart for while Loop
25
Common Error: Infinite Loop while (year < 20) { balance = balance + balance * rate / 100; } while (year > 0) { year++; // oops, meant -- } Loops run forever--must kill program
26
Common Error: Off-by-1 Error year = 0; while (balance < 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 < or <=?
27
Avoiding Off-by-1 Error Run through a simple example: target balance = $20,000, interest rate 50% after one year: balance = $15,000 after two years: balance = $22,500 Therefore: year must start at 0 interest rate 100% after one year: balance = $20,000 loop should stop Therefore: must use < 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 value; do{ String input = JOptionPane.showInputDialog( "Please enter a positive number"); value = Integer.parseInt(input); } while (input <= 0);
29
Flowchart for do Loop
30
for (initialization; condition; update) statement Example: for (int i = 1; i <= n; i++){ double interest = balance * rate / 100; balance = balance + interest; } Equivalent to: initialization; while (condition){ statement; update; } for Statement
31
Flowchart for for Loop
32
Common Errors: Semicolons A semicolon that shouldn't be there sum = 0; for (i = 1; i <= 10; i++); sum = sum + i; System.out.println(sum);
33
Common Errors: Semicolons A semicolon that shouldn't be there sum = 0; i = 1; while ( i <= 10) ; { sum = sum + i; i = i + 1; } System.out.println(sum);
34
Nested Loops Create triangle pattern [] [][] [][][] [][][][] Loop through rows for (int i = 1; i <= n; i++) { // make triangle row }
35
Make triangle row is another loop for (int j = 1; j <= i; j++) r = r + "[]"; r = r + "\n"; Put loops together => Nested loops for (int i = 1; i <= width; i++) { // make triangle row for (int j = 1; j <= i; j++) r = r + "[]"; r = r + "\n"; }
36
Reading Input Values General pattern: boolean done = false; while (!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 < s.length(); i++) { char ch = s.charAt(i); process ch }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.