-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathArithmetic.java
More file actions
59 lines (49 loc) · 1.49 KB
/
Arithmetic.java
File metadata and controls
59 lines (49 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Avoid float and double if exact answers are required!! - Page 48
package effectivejava.chapter8.item48;
import java.math.BigDecimal;
public class Arithmetic {
public static void main(String[] args) {
System.out.println(1.03 - .42);
System.out.println();
System.out.println(1.00 - 9 * .10);
System.out.println();
howManyCandies1();
System.out.println();
howManyCandies2();
System.out.println();
howManyCandies3();
}
// Broken - uses floating point for monetary calculation!
public static void howManyCandies1() {
double funds = 1.00;
int itemsBought = 0;
for (double price = .10; funds >= price; price += .10) {
funds -= price;
itemsBought++;
}
System.out.println(itemsBought + " items bought.");
System.out.println("Change: $" + funds);
}
public static void howManyCandies2() {
final BigDecimal TEN_CENTS = new BigDecimal(".10");
int itemsBought = 0;
BigDecimal funds = new BigDecimal("1.00");
for (BigDecimal price = TEN_CENTS; funds.compareTo(price) >= 0; price = price
.add(TEN_CENTS)) {
itemsBought++;
funds = funds.subtract(price);
}
System.out.println(itemsBought + " items bought.");
System.out.println("Money left over: $" + funds);
}
public static void howManyCandies3() {
int itemsBought = 0;
int funds = 100;
for (int price = 10; funds >= price; price += 10) {
itemsBought++;
funds -= price;
}
System.out.println(itemsBought + " items bought.");
System.out.println("Money left over: " + funds + " cents");
}
}