Write a java class encapsulating the concept of coins, assuming that Coins has t
ID: 3791684 • Letter: W
Question
Write a java class encapsulating the concept of coins, assuming that Coins has the following attributes: a number of quarters, a number of dimes, a number of nickels and a number of pennies. Include constructors, accessors, mutators, and methods toString() and equals(). Also code the following other methods: one returning the total amount of money, and the others returning the money in quarters (for instance, 0.75 if there are three quarters), in dimes, in nickels, and in pennies. Write a client class to test all the methods in your class. Print the total amount of money in dollar notation with two significant digits after the decimal point.
Explanation / Answer
import java.text.DecimalFormat;
public class Money
{
private int quarters;
private int dimes;
private int nickels;
private int pennies;
// Constructors - - - - - - - - - - - - - -
public Money() {
// default, no-argument constructor
// defers to worker signature
this(0, 0, 0, 0);
}
public Money(int q, int, d, int n, int p) {
// construction requires numbers of
// q(uarters), d(imes), n(ickels), and
// p(ennies)
setQuarters( q );
setDimes( d );
setNickels( n );
setPennies( p );
}
// Utility - - - - - - - - - - - - - - - - -
public String toString() {
String fmt = "$###,###.###";
DecimalFormat dFmt = new DecimalFormat( fmt );
return dFmt.format( 01*getAmtTotal() );
}
function boolean equals( double dollars ) {
return dollars == .01*getAmtTotal();
}
// Public Accessors and Mutators - - - - - -
public int getAmtTotal() {
return getAmtQuarters() + getAmtDimes() +
getAmtNickels() + getAmtPennies();
}
public int getAmtQuarters() {
return 25*quarters();
}
public int getAmtDimes() {
return 10*dimes();
}
public int getAmtNickels() {
return 5*nickels;
}
public int getAmtPennies() {
return pennies;
}
public int getQuarters() {
return quarters;
}
public int setQuarters( int q ) {
quarters = q;
}
public int getDimes() {
return dimes;
}
public int setDimes( int d ) {
dimes = d;
}
public int getNickels() {
return nickels;
}
public int setNickels( int n ) {
nickels = n;
}
public int getPennies() {
return pennies;
}
public int set( int p ) {
pennies = p;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.