Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialcoder5837
1,535 PointsI do not understand whatsoever how to do this challenge can someone please help me
We're basically trying to write a brand new shopping car system for the website. I'm trying to make it easier to add things to the cart. and have the default amount as 1.
public class Example {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
Product pez = new Product("Cherry PEZ refill (12 pieces)");
cart.addItem(pez, 5);
/* Since a quantity of 1 is such a common argument when adding a product to the cart,
* your fellow developers have asked you to make the following code work, as well as keeping
* the ability to add a product and a quantity.
*/
Product dispenser = new Product("Yoda PEZ dispenser");
Uncomment the line following this comment,
after adding a new method using method signatures,
to solve their request in ShoppingCart.java
cart.addItem(dispenser);
}
}
public class ShoppingCart {
public void addItem(Product item, int quantity) {
System.out.printf("Adding %d of %s to the cart.%n", quantity, item.getName());
/* Other code omitted for clarity. Please imagine
lots and lots of code here. Don't repeat it.
*/
}
public void addItem(Product item);
addItem int quantity (1);
}
public class Product {
/* Other code omitted for clarity, but you could imagine
it would store price, options like size and color
*/
private String mName;
public Product(String name) {
mName = name;
}
public String getName() {
return mName;
}
}
1 Answer
bobkingstone
27,869 PointsHi
The question is asking you to make the:
cart.addItem(dispenser);
function call work, as at the moment ShoppingCart.additem requires you to pass it two parameters, item and the quantity.
So it is necessary for you create an overloaded function, which basically means a function with the same name but with a different number of parameters within the ShoppingCart class. e.g:
current function: addItem(item,qty)
additional function: addItem(item)
Once you have created this new function you can call the original function with the default parameter of 1 e.g.:
public void addItem(Product item) {
this.addItem(item, 1);
}
Hope this helps Bob
coder5837
1,535 Pointscoder5837
1,535 Pointshi bob, could you help me with my previous question? Thank you!