if Statement if amount balance balance balance amount
if Statement if (amount <= balance) balance = balance - amount;
if/else Statement if (amount <= balance) balance = balance - amount; else balance = balance. OVERDRAFT_PENALTY;
Block Statement if (amount <= balance) { double new. Balance = balance - amount; balance = new. Balance; } Note: block allows more than one ‘statement’ to be combined, to form a new ‘statement’
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 =
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);
· It prints: sqrt(2)squared minus 2 is not 0 but 4. 440892098500626 E-16 · Don't use == to compare floating-point numbers
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|)
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. equals. Ignore. Case("Y"))
Lexicographic Comparison · s. compare. To(t) < 0 means: s comes before t in the dictionary · "car"comes before "cargo" comes before "cathode" · All uppercase letters come before lowercase: "Hello" comes before "car"
Lexicographic Comparison
Object Comparison · = = tests for identical object · equals for identical object content · Rectangle cereal. Box = new Rectangle(5, 10, 20, 30); Rectangle oatmeal. Box = new Rectangle(5, 10, 20, 30); Rectangle r = cereal. Box; · cereal. Box != oatmeal. Box, but cereal. Box. equals(oatmeal. Box) · cereal. Box == r Caveat: equals must be defined for the class (chap 11)
Object Comparison
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 · show. Input. Dialog returns null if the user hit the cancel button: String input = JOption. Pane. show. Input. Dialog(". . . "); if (input != null) {. . . } · null is not the same as the empty string ""
Multiple Alternatives • if (condition 1) statement 1; else if (condition 2) statement 2; else if (condition 3) statement 3; else statement 4; • The first matching condition is executed. • Order matters.
Multiple Alternatives · Order matters: if (condition 1) Statement 1; else if (condition 2) Statement 2; else if (condition 3) Statement 3; else // option – executes of all conditions fail Statement 4;
Nested Branches • Branch inside another branch if (condition 1) { if (condition 1 a) statement 1 a; else statement 1 b; } else statement 2;
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
Predicate Method · return type boolean · Example: public boolean is. Overdrawn() { return balance < 0; } · Use in conditions if (harrys. Checking. is. Overdrawn()). . . · Useful predicate methods in Character class: is. Digit is. Letter is. Upper. Case is. Lower. Case · if (Character. is. Upper. Case(ch)). . .
Boolean Operators · ! not · && and (short circuited) · || or (short circuited)
Truth Tables
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!!!
Investment with Compound Interest Invest $10, 000, 5% interest, compounded annually When will the balance be at least $20, 000?
while Statement while (condition) statement; //repeats the statement while the condition is true while (balance < target. Balance){ year++; double interest = balance * rate / 100; balance = balance + interest; }
Flowchart for while Loop
Common Error: Infinite Loop while (year < 20) { balance = balance + balance * rate / 100; } while (year > 0) { year++; // oops, meant -} Loops run forever--must kill program
Common Error: Off-by-1 Error year = 0; while (balance < target. Balance){ 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 <=?
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
do Statement • Executes loop body at least once: do statement while (condition); • Example: Validate input double value; do{ String input = JOption. Pane. show. Input. Dialog( "Please enter a positive number"); value = Integer. parse. Int(input); } while (input <= 0);
Flowchart for do Loop
for Statement 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; }
Flowchart for Loop
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);
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);
Nested Loops · Create triangle pattern [] [][][] · Loop through rows for (int i = 1; i <= n; i++) { // make triangle row }
· 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"; }
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"
Another option… • General pattern: while (end of input != read input ){ process input }
String Tokenization · String. Tokenizer breaks up string into tokens · By default, white space separates tokens · "4. 3 7 -2" breaks into three tokens: "4. 3", "7", "-2" String. Tokenizer tokenizer = new String. Tokenizer(a String); while (tokenizer. has. More. Tokens()) { String token = tokenizer. next. Token(); process token }
Traversing Characters in String s. char. At(i) is the ith character of the string s for (int i = 0; i < s. length(); i++) { char ch = s. char. At(i); process ch }
- Slides: 39