if (amount <= balance) balance = balance - amount;
if (amount <= balance) balance = balance - amount; else balance = balance - OVERDRAFT_PENALTY;
balance = balance - amount;
if (balance >= amount) balance = balance - amount;
Also loop statements – Chapter 6
{ double newBalance = balance - amount; balance = newBalance; }
Java | Math Notation | Description |
---|---|---|
> | > | Greater than |
>= | ≥ | Greater than or equal |
< | < | Less than |
<= | ≤ | Less than or equal |
== | = | Equal |
!= | ≠ | Not equal |
a = 5; // Assign 5 to a if (a == 5) . . . // Test whether a equals 5
amount + fee <= balance
Consider the code fragment that is intended to fix the withdraw method so that the account balance can't be negative.
public void withdraw(double amount) { if (amount <= balance) // Make sure the account isn't overdrawn newBalance = balance - amount; balance = newBalance; }
What is wrong with 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);
final double EPSILON = 1E-14; if (Math.abs(x - y) <= EPSILON) // x is approximately equal to y
if (string1.equals(string2)) . . .
if (string1 == string2) // Not useful
if (string1.equalsIgnoreCase(string2))
Rectangle box1 = new Rectangle(5, 10, 20, 30); Rectangle box2 = box1; Rectangle box3 = new Rectangle(5, 10, 20, 30);
String middleInitial = null; // Not set if ( . . . ) middleInitial = middleName.substring(0, 1);
if (middleInitial == null) System.out.println(firstName + " " + lastName); else System.out.println(firstName + " " + middleInitial + ". " + lastName);
Consider the following definitions.
String a = "1"; String b = "one"; double x = 1; double y = 3 * (1.0 / 3);
How many of the following comparisons are syntactically incorrect? How many of them are syntactically correct, but logically questionable?