这是我尝试添加所有内容的方法。我想要做的是将一系列硬币加起来,命名为 penny、dime 等。我在枚举中给了它们一个值。但是我如何访问数组中的每个硬币,然后将它们的值相加呢?
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!
}
这里是定义枚举值的地方。
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;
}
}
///// 我刚刚添加了我的硬币类。
import java.util.Random;
public class Coin
{
public static long SEED = System.currentTimeMillis();
public static Random RANDOM = new Random(SEED);
//private instance variables denomination, year, and sideUp: year is an int, denomination is of type CoinName and sideUp is of type CoinSide
private CoinName denomination;
private CoinSide sideUp;
private int year;
public Coin(CoinName denomination,int year)
{
this.denomination = denomination;
this.year = year;
int side = Coin.RANDOM.nextInt(2);
if (side == 0)
{
sideUp = CoinSide.HEADS;
}
else
sideUp = CoinSide.TAILS;
}
//Accessors for denomination, year and sideUp
public CoinName setDenomination()
{
int i = 0;
i = Coin.RANDOM.nextInt(6);
if (i == 0)
{
denomination = CoinName.PENNY;
}
if (i == 1)
{
denomination = CoinName.NICKEL;
}
if (i == 2)
{
denomination = CoinName.DIME;
}
if (i == 3)
{
denomination = CoinName.QUARTER;
}
if (i == 4)
{
denomination = CoinName.FIFTY_CENT;
}
if (i == 5)
{
denomination = CoinName.DOLLAR;
}
return denomination;
}
public CoinName getDenomination()
{
return denomination;
}
public void setSideUp(CoinSide sideUp)
{
sideUp = sideUp;
}
public CoinSide getSideUp()
{
return sideUp;
}
public void setYear(int year)
{
year = RANDOM.nextInt(2013-1873) + 1873;
}
public int getYear()
{
return year;
}
//the standard toString method that prints out a coin in the format “PENNY/1990/HEADS”
public String toString()
{
return denomination + "/" + year + "/" + sideUp;
}
//the standard equals method that checks if two Coin objects are equal – they are equal if the denominations are identical
public boolean equals(Object obj)
{
if (obj instanceof Coin){
Coin d = (Coin)obj;
if (this.getDenomination()==d.getDenomination())
return true;
else
return false;
}
return false;
}
public void toss()
{
//flip the coin
//Use the object RANDOM to generate random numbers
int side = Coin.RANDOM.nextInt(2);
if (side == 0)
{
sideUp = CoinSide.HEADS;
}
else
sideUp = CoinSide.TAILS;
}
}