Reputation: 2454
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?
Upvotes: 0
Views: 202
Reputation: 60414
The general point here is that you've defined purchases
so that it must only contain CreditCard
instances:
private CreditCard[] purchases;
The type you specify here controls what you're allowed to place in it later. You then attempt to place a double
into the array:
purchases[numPurchases] = amount;
But you just told the compiler that purchases
is only allowed to contain CreditCard
s!
You need to wrap your double
in a CreditCard
instance first.
Imagine you have the following class:
public class CreditCard {
private double amount;
public CreditCard(double amount) {
this.amount = amount;
}
}
Now you can do this:
purchases[numPurchases] = new CreditCard(amount);
...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 a purchases
array, then it's probably a purchase, not the credit card itself.
Upvotes: 1
Reputation: 8677
you need to create a CreditCard instance and add that to your array
CreditCard creditCard = new CreditCard();
creditCard.setAmount(amount);
purchases[numPurchases]= creditCard;
Upvotes: 1