A shop keeps its orders in a cart. Build two classes that work together: a LineItem is one row of the cart (a product, its price and how many were bought), and a Cart holds many rows and adds them up. The cart has line items (composition), it is not one.
LineItem
class LineItem(val name: String, val price: Double, val quantity: Int): the primary constructor declares the three fields.def subtotal(): Doublereturnsprice * quantity.
Cart
- It keeps its items in
private val items = scala.collection.mutable.ArrayBuffer[LineItem](). def add(item: LineItem): Unitappends the item to the buffer.def total(): Doublereturns the sum of the subtotals of all items: startvar sum = 0.0, loop withfor (item <- items), returnsum.
Rules:
- The total is worked out every time it is asked for, from the items in the cart at that moment. Adding an item later changes the next total.
- An empty cart has a total of
0. - An item with price 5 and quantity 3 has a subtotal of 15.
- Prices in the driver are whole numbers.
The driver lives in Solution.mainFunction() and uses .toInt to print whole numbers.
The driver (already in the starter code, don't change it) creates an empty cart, checks one subtotal, then fills a cart and prints the total twice:
class Solution {
def mainFunction(): Unit = {
val empty = Cart()
println("Empty: " + empty.total().toInt)
val apple = LineItem("Apple", 5.0, 3)
println("Subtotal: " + apple.subtotal().toInt)
val cart = Cart()
cart.add(apple)
cart.add(LineItem("Bread", 20.0, 3))
println("Total: " + cart.total().toInt)
cart.add(LineItem("Milk", 10.0, 2))
println("Total: " + cart.total().toInt)
}
}
Expected output:
Empty: 0 Subtotal: 15 Total: 75 Total: 95
Write
LineItem with its primary constructor first, then Cart.
for (item <- items) { sum += item.subtotal() }
class LineItem(val name: String, val price: Double, val quantity: Int) {
def subtotal(): Double = {
return price * quantity
}
}
class Cart {
private val items = scala.collection.mutable.ArrayBuffer[LineItem]()
def add(item: LineItem): Unit = {
items.append(item)
}
def total(): Double = {
var sum = 0.0
for (item <- items) {
sum += item.subtotal()
}
return sum
}
}
class Solution {
def mainFunction(): Unit = {
val empty = Cart()
println("Empty: " + empty.total().toInt)
val apple = LineItem("Apple", 5.0, 3)
println("Subtotal: " + apple.subtotal().toInt)
val cart = Cart()
cart.add(apple)
cart.add(LineItem("Bread", 20.0, 3))
println("Total: " + cart.total().toInt)
cart.add(LineItem("Milk", 10.0, 2))
println("Total: " + cart.total().toInt)
}
}
Free plan: 30 tutor messages. Premium is unlimited.
