Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MainProgram {
- public static void main(String[] args) {
- Money a = new Money(10, 0);
- Money b = new Money(3, 50);
- Money c = a.minus(b);
- System.out.println(a); // 10.00e
- System.out.println(b); // 3.50e
- System.out.println(c); // 6.50e
- c = c.minus(a); // NB: a new Money object is created, and is placed "at the end of the strand connected to c"
- // the old 6.5 euros at the end of the strand disappears and the Java garbage collector takes care of it
- System.out.println(a); // 10.00e
- System.out.println(b); // 3.50e
- System.out.println(c); // 0.00e
- }
- }
- public class Money {
- private final int euros;
- private final int cents;
- public Money(int euros, int cents) {
- if (cents > 99) {
- euros = euros + cents / 100;
- cents = cents % 100;
- }
- this.euros = euros;
- this.cents = cents;
- }
- public int euros() {
- return this.euros;
- }
- public int cents() {
- return this.cents;
- }
- public String toString() {
- String zero = "";
- if (this.cents < 10) {
- zero = "0";
- }
- return this.euros + "." + zero + this.cents + "e";
- }
- public boolean lessThan(Money compared) {
- if (this.euros < compared.euros) {
- return true;
- }
- if (this.euros == compared.euros && this.cents < compared.cents) {
- return true;
- }
- return false;
- }
- public Money plus(Money addition) {
- Money newMoney = new Money(addition.euros + this.euros, addition.cents + this.cents);// create a new Money object that has the correct worth
- return newMoney;
- }
- public Money minus(Money decreaser) {
- int e =decreaser.euros-this.euros;
- int c= decreaser.cents-this.cents;
- Money newMinus = new Money (e,c);
- return newMinus;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement