Write a class encapsulating the concept of coins, assuming that coins have the f
ID: 3546254 • Letter: W
Question
Write a class encapsulating the concept of coins, assuming that coins have the following attributes: a 66 of quarters, a number of dimes, a number of nickels, and a number of pennies. Include a constructor, the accessors and mutators, and methods toString and equals. Also code the following methods: one returning the total amount of money in dollar notation with two significant digits after the deimal point, and other returning the money in quarters (for instance, 0.75 if there are three quarters), in dimes, in nickles, and in pennies. Write a client class to test all the methods in your class. Creat a diagram for Coin class. Provide a JavaDoc comments including the precoditions and postconditions for the set methods.
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.