How would I add enumerated type values in an array
Heres the method where I try to add everything. What im trying to do is
add up a series of coins, which are named penny,dime...etc. And i gave all
of them a value within the enum. But how do I access each of the coins
within the array, then add up their values?
public double totalValue(Coin[] coins)
{
double sum = 0;
//computes and returns the monetary value of all the coins in the jar
for(int i = 0; i < coins.length; i++)
{
double coinValue = coins[i].CoinName.getCoinValue();
sum = sum + coins[i];
System.out.println(sum);
}
return sum; //change this!
}
and here is where the values for the enum are defined.
public enum CoinName
{
PENNY(.01), NICKEL(.05), DIME(.10), QUARTER(.25), FIFTY_CENT(.50),
DOLLAR(1.0);
private double value;
private double coinValue;
private CoinName(double value)
{
this.coinValue = value;
}
public double getCoinValue()
{
return coinValue;
}
}
A Coin has a denomination, which holds the value of the coin. With how you have defined things, to sum the values of an array of coins you have to first get the denomination and then extract the value from it:
ReplyDeletefor(int i = 0; i < coins.length; i++)
{
CoinName denomination = coins[i].getDenomination();
sum = sum + denomination.getCoinValue();
System.out.println(sum);
}
Note that for this to work the array of coins must be full, with no null values, and each coin must have a denomination.