In: Computer Science
Please add comments to this code!
JAVA code:
import java.util.ArrayList;
public class ShoppingCart {
private final ArrayList<ItemOrder> itemOrder;
private double total = 0;
private double discount = 0;
ShoppingCart() {
itemOrder = new
ArrayList<>();
total = 0;
}
public void setDiscount(boolean selected) {
if (selected) {
discount = total * .1;
}
}
public double getTotal() {
total = 0;
itemOrder.forEach((order)
-> {
total
+= order.getPrice();
});
return total - discount;
}
/***
*
* @param order
* @return
*/
public boolean add(ItemOrder order) {
for (int i = 0; i <
itemOrder.size(); i++) {
ItemOrder temp = itemOrder.get(i);
if
((temp.getItem()).equals(order.getItem())) {
itemOrder.set(i, order);
return true;
}
}
itemOrder.add(order);
return true;
}
}
Thanks!!
import java.util.ArrayList;
//Class name Shopping cart
public class ShoppingCart {
//ArrayList of type ItemOrder
private final ArrayList<ItemOrder> itemOrder;
private double total = 0;
private double discount = 0;
//Default Constructor initiliaze the member vaiables to 0
ShoppingCart() {
itemOrder = new
ArrayList<>();
total = 0;
}
public void setDiscount(boolean selected) {
//Sets the discount for a particular total
amount
if (selected) {
//Discount is 10 % of total
discount = total * .1;
}
}
//Calculate the total amount of all the orders in the array list and return the total - discount amount
public double getTotal() {
total = 0;
itemOrder.forEach((order)
-> {
total
+= order.getPrice();
});
return total - discount;
}
/***
*
* @param order
* @return
*/
//Add an item to the array list.
//If the item already exists in the array list then
//Replace the order with the new order and return true
//Else if it is not present then add to the arraylist at
the end
public boolean add(ItemOrder order) {
for (int i = 0; i <
itemOrder.size(); i++) {
ItemOrder temp = itemOrder.get(i);
if
((temp.getItem()).equals(order.getItem())) {
itemOrder.set(i, order);
return true;
}
}
itemOrder.add(order);
return true;
}
}