mojito Member
Posts : 2 Join date : 2011-06-21
| Subject: Problem with Class method Thu Jun 23, 2011 5:49 am | |
| Hey I'm new to Java and I was trying to write this class but I'm not sure how to get the last method, add(), to work properly. If someone could help it would be appreciated - Code:
-
import java.text.DecimalFormat;
public class BritishMoney { private int pounds; private int shillings; private int pence; DecimalFormat formatter = new DecimalFormat("0.00"); BritishMoney (int x, int y, int z) { pounds = x; shillings = y; pence = z; normalize(); } private void normalize() { pounds = pounds + shillings/20; shillings = shillings % 20 + pence /12; pence = pence % 12; } public int toPence() { return pence; } public String toString() { return ("Pounds: " + pounds + " Shillings: " + shillings + " Pence: " + pence); } public String toDecimalPounds() { double decimalPound; double penceAmount; double poundAmount; String formatted; penceAmount = (shillings * 12) + pence; poundAmount = (pounds * 240) + penceAmount; decimalPound = poundAmount / 240; formatted = formatter.format(decimalPound); return formatted; } public BritishMoney add(BritishMoney other) { BritishMoney newMoney = new BritishMoney(pounds, shillings, pence); return newMoney + other; } }
|
|
toxicity Member
Posts : 6 Join date : 2011-06-21
| Subject: Re: Problem with Class method Thu Jun 23, 2011 5:50 am | |
| You cannot add two objects together, and Java does not support operator overloads. You need to add each of the fields. This is way more work than you need since you're returning a new object: - Code:
-
public BritishMoney add(BritishMoney other) { int pounds = this.pounds + other.pounds; int shillings = this.shillings + other.shillings; int pence = this.pence + other.pence; return new BritishMoney(pounds, shillings, pence); }
If the intention is to add it to the current existing BritishMoney than: - Code:
-
public void add(BritishMoney other) { this.pounds += other.pounds; this.shillings += other.shillings; this.pence += other.pence; this.normalize(); }
And can be returned after modification as well: - Code:
-
public BritishMoney add(BritishMoney other) { this.pounds += other.pounds; this.shillings += other.shillings; this.pence += other.pence; this.normalize(); return this; }
|
|