-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMonetaryValue.java
More file actions
74 lines (61 loc) · 1.75 KB
/
MonetaryValue.java
File metadata and controls
74 lines (61 loc) · 1.75 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
public class MonetaryValue {
private int cents;
public MonetaryValue() {
cents = 0;
}
public MonetaryValue(double dollars) {
double noDecDollars = dollars * 100;
cents = (int) noDecDollars;
}
public MonetaryValue(MonetaryValue oldMonetaryValue) {
this.cents = oldMonetaryValue.cents;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof MonetaryValue) {
MonetaryValue other = (MonetaryValue) obj;
return this.cents == other.cents;
}
return false;
}
@Override
public String toString() {
double dollars = (double) cents / 100;
return String.format("$%.2f", dollars);
}
public boolean isLessThan(MonetaryValue compareMonetaryValue) {
return this.cents < compareMonetaryValue.cents;
}
public boolean isGreaterThan(MonetaryValue compareMonetaryValue) {
return this.cents > compareMonetaryValue.cents;
}
public boolean isNegative() {
return this.cents < 0;
}
public double doubleValue() {
return (double) cents / 100;
}
public boolean add(MonetaryValue money) {
if (money.cents < 0) {
return false;
} else {
this.cents += money.cents;
return true;
}
}
public boolean subtract(MonetaryValue money) {
if (money.cents < 0) {
return false;
} else {
this.cents -= money.cents;
return true;
}
}
public static MonetaryValue read(java.util.Scanner sc) {
if (sc.hasNextDouble()) {
MonetaryValue newValue = new MonetaryValue(sc.nextDouble());
return newValue;
}
return null;
}
}