I am attempting to convert arrays of primitive double values to objects. As a result I am getting a “type mismatch error”
private double[]purchases;
to
private CreditCard[]purchases;
then when I try to add a value to the array
public void purchase(double amount)throws Exception
{
if (numPurchases<purchases.length)
if (amount >0 )
if(amount+balance<=creditLimit)
if( GregorianCalendar.getInstance().getTimeInMillis()<=expDate.getTimeInMillis())
{
balance+=amount;
purchases[numPurchases]= amount;
numPurchases++;
}
else
{
throw new Exception("card expired");
}
else{
throw new Exception("insufficient credit");
}
else{
throw new Exception("invalid amount");
}
else{
throw new Exception("exceeded number of allowed purchases");
}
}
the error message says type mismatch for amount “cannot convert from double to CreditCard
how can I correct the code to allow me to add purchase amounts to the array?
The general point here is that you’ve defined
purchasesso that it must only containCreditCardinstances:The type you specify here controls what you’re allowed to place in it later. You then attempt to place a
doubleinto the array:But you just told the compiler that
purchasesis only allowed to containCreditCards!You need to wrap your
doublein aCreditCardinstance first.Imagine you have the following class:
Now you can do this:
…because the thing you’re putting into the array has the correct type.
On a side note, consider renaming your class to
CreditCardPurchase, if that’s what it really represents. The name of your class should say something about what it is. If it’s going into apurchasesarray, then it’s probably a purchase, not the credit card itself.