JAVA: Representing money as a real quantity (float or double) may result in roun
ID: 3838357 • Letter: J
Question
JAVA:
Representing money as a real quantity (float or double) may result in round-off errors. To perform exact computations, the dollars and cents could be treated as separate integers. The interface for a Money class is shown below. Add all necessary elements (declarations & executable statements) to implement the class. Assume that all amounts are non-negative and valid.
public class Money{
//Constructor for an instance given dollars and cents
public Money (int dollars, int cents){
}
//Constructor for an instance given an existing instance
public Money(Money m) {
}
//This method creates a new instance that is the sum of the current instance and the given instance
public Money sum(Money m) {
}
//this method determines whether the current instance represents the same value as the given instance
public boolean equals(Object o){
}
//this method creates an appropriate string representation (eg, $nnn.nn)
public String toString(){
}
Explanation / Answer
class Money{
private int dollars;
private int cents;
//Constructor for an instance given dollars and cents
public Money (int dollars, int cents){
this.dollars = dollars;
this.cents = cents;
}
//Constructor for an instance given an existing instance
public Money(Money m) {
this.dollars = m.dollars;
this.cents = m.cents;
}
//This method creates a new instance that is the sum of the current instance and the given instance
public Money sum(Money m) {
dollars = dollars + m.dollars;
cents = cents + m.cents;
return this;
}
//this method determines whether the current instance represents the same value as the given instance
public boolean equals(Money m){
if(this.dollars == m.dollars && this.cents == m.cents )
return true;
else
return false;
}
//this method creates an appropriate string representation (eg, $nnn.nn)
public String toString(){
return "$"+dollars + "."+cents;
}
}
class TestMoney
{
public static void main (String[] args)
{
Money m1 = new Money(14,67);
Money m2 = new Money(56,31);
System.out.println("m1 = "+ m1);
System.out.println("m2 = "+ m2);
System.out.println(" sum = "+ m1.sum(m2));
if(m1.equals(m2))
System.out.println("m1 is equal to m2");
else
System.out.println("m1 is not equal to m2");
}
}
Output:
m1 = $14.67
m2 = $56.31
sum = $70.98
m1 is not equal to m2
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.