I'm working on an Ice Cream program in Java. I have to make sure that each topping can only be added once. I was just wondering if anyone had any pointers so I could get started.
3 Replies - 97 Views - Last Post: 02 October 2012 - 06:21 PM
#1
How to make sure that an object has not already been added?
Posted 02 October 2012 - 02:08 PM
Replies To: How to make sure that an object has not already been added?
#2
Re: How to make sure that an object has not already been added?
Posted 02 October 2012 - 02:15 PM
Can you describe your design or show some code? If you have the typical, beginning programmer, all in a main() method design, then whether a topping has been added could be tracked with a boolean, toppingAdded = true or false, depending on whether a topping had been added.
But if you have a more OOP design and have a Dessert class with Sundae and IceCreamCone as subclasses, then those objects should have a variable that keeps track of the toppings added.
It's hard to say what should or could be done in your case without some code or an idea of your existing design.
But if you have a more OOP design and have a Dessert class with Sundae and IceCreamCone as subclasses, then those objects should have a variable that keeps track of the toppings added.
It's hard to say what should or could be done in your case without some code or an idea of your existing design.
#3
Re: How to make sure that an object has not already been added?
Posted 02 October 2012 - 05:24 PM
This is part of the code I have. All three methods are in different classes in different classes, to make sure that only one topping is added
public boolean isDuplicate(IceCreamTopping check)
{
boolean topping = false;
if(ice_cream instanceof IceCreamTopping)
{
topping = ice_cream.equals(check);
}
return topping;
}
}
public boolean isDuplicate()
{
return super.isDuplicate(this);
}
public boolean equals(IceCreamTopping ict)
{
if(ict instanceof Nuts)
{
return true;
}
else
return false;
}
#4
Re: How to make sure that an object has not already been added?
Posted 02 October 2012 - 06:21 PM
You can try creating a variable containing all the toppings and a method with a collection that has them and you can check for that.
Pseudocode:
I'm pretty sure there's a Collection method that checks if something exists in a list. Or you could just loop if you want and see if it's in there.
Pseudocode:
public IceCream{
public Collection<Topping> toppings;
public void addTopping(Topping topping){
if(this.toppings.contains(topping){
Method.invoke(FuryOfZeus);
} else {
toppings.add(topping);
}
}
}
I'm pretty sure there's a Collection method that checks if something exists in a list. Or you could just loop if you want and see if it's in there.
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote




|