using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Chapter4_6Expanded { /**************************************** * This class calucates the change returned for * amounts less than a dollar. * it creates constants for the values of * quarters, dimes and nickles * and also fields and properties for each * denomination. There is a seperate method for * each denomination. The first, for quarters * divides the amount passed to the class through * the constructor by the constant Q (25) and then * assigns the result to the property Quarters, * and the modulus to the property Remainders. * Each of the other methods takes the remainder * and divides it by the appropriate constant * Then assigns the quotient to the appropriate * property and the modulus back to remainder * The methods are private. The only visible * public method is the overridden ToString() * method which returns all the results as a * string. It uses a built in object called the * String Builder to arrange the string to * be returned * Steve Conger, 10/20/2008 * ******************************************/ class Change { //constants private const int Q = 25; private const int D = 10; private const int N = 5; //constructor public Change(int amt) { Amount = amt; Quarters = 0; Dimes = 0; Nickles = 0; //the constructor calls the methods //making sure they are executed in the proper //order CalcQuarters(); CalcDimes(); CalcNickles(); Pennies = Remainder; } //private fields and properties private int quarters; public int Quarters { get { return quarters; } set { quarters = value; } } private int dimes; public int Dimes { get { return dimes; } set { dimes = value; } } private int nickles; public int Nickles { get { return nickles; } set { nickles = value; } } private int pennies; public int Pennies { get { return pennies; } set { pennies = value; } } private int remainder; public int Remainder { get { return remainder; } set { remainder = value; } } private int amount; public int Amount { get { return amount; } set { amount = value; } } //methods to convert values private void CalcQuarters() { Quarters = Amount / Q; Remainder = Amount % Q; } private void CalcDimes() { Dimes = Remainder / D; Remainder %= D; } private void CalcNickles() { Nickles = Remainder / N; Remainder %= N; } public override string ToString() { StringBuilder builder=new StringBuilder(); builder.Append("The correct change for "); builder.Append(Amount); builder.Append(" cents "); builder.AppendLine(); builder.Append("is "); builder.Append(Quarters); builder.Append(" quarters, "); builder.Append(Dimes); builder.Append(" dimes, "); builder.Append(Nickles); builder.Append(" nickles, and "); builder.Append(Pennies); builder.Append(" pennies. "); return builder.ToString(); } } }