The Snack Machine: A good way to study for a programming exam is to write code!
Study and UML analyze this program.
Try rewriting it by yourself.
This covers more of the key concepts in KOTLIN.
Can you spot them?
// Snack data class to represent each snack item
data class Snack(val name: String, var price: Double, var quantity: Int)
// Singleton VendingMachine object
object VendingMachine {
var cashInMachine: Double = 0.0
val snacksInventory = mutableListOf(
Snack("Ketchup Chips", 2.50, 10),
Snack("Coffee Crisp", 1.75, 10),
Snack("Smarties", 1.50, 10),
Snack("Hickory Sticks", 2.00, 10),
Snack("Aero Bar", 1.75, 10),
Snack("Lay's Chips", 2.25, 10),
Snack("Doritos", 2.50, 10),
Snack("Kit Kat", 1.75, 10),
Snack("Oh Henry!", 1.75, 10),
Snack("Reese's Cups", 2.00, 10)
)
// Method to display available snacks
fun displaySnacks() {
println("\nAvailable Snacks:")
snacksInventory.forEachIndexed { index, snack ->
println("${index + 1}. ${snack.name} - \$${snack.price} (${snack.quantity} left)")
}
}
// Method to purchase a snack
fun purchaseSnack(customer: Customer, snackIndex: Int) {
if (snackIndex !in snacksInventory.indices) {
println("Invalid selection.")
return
}
val snack = snacksInventory[snackIndex]
if (snack.quantity <= 0) {
println("Sorry, ${snack.name} is out of stock.")
return
}
if (customer.cashInWallet < snack.price) {
println("Sorry, ${customer.name}, you don't have enough money.")
return
}
// Process transaction
customer.cashInWallet -= snack.price
cashInMachine += snack.price
snack.quantity -= 1
customer.snacksInKnapsack.add(snack.name)
println("Thank you, ${customer.name}! You purchased a ${snack.name}.")
}
// Method to display vending machine report
fun report() {
println("\n--- Vending Machine Report ---")
println("Cash in Machine: \$${"%.2f".format(cashInMachine)}")
println("Snack Inventory:")
snacksInventory.forEach {
println("${it.name}: ${it.quantity} left")
}
println("------------------------------\n")
}
}
// Customer class (multiple instances allowed)
class Customer(val name: String, var cashInWallet: Double) {
val snacksInKnapsack = mutableListOf<String>()
fun displayCustomerInfo() {
println("\nCustomer: $name")
println("Cash in Wallet: \$${"%.2f".format(cashInWallet)}")
println("Snacks in Knapsack: ${if (snacksInKnapsack.isEmpty()) "None" else snacksInKnapsack.joinToString(", ")}")
}
}
// Main function to simulate interaction
fun main() {
val customers = mutableListOf(
Customer("Alice", 10.0),
Customer("Bob", 5.0)
)
println("Welcome to the Kotlin Vending Machine!")
var continueShopping = true
while (continueShopping) {
println("\nSelect Customer:")
customers.forEachIndexed { index, customer ->
println("${index + 1}. ${customer.name}")
}
println("${customers.size + 1}. Exit")
val customerChoice = readLine()?.toIntOrNull()
if (customerChoice == null || customerChoice !in 1..(customers.size + 1)) {
println("Invalid choice. Try again.")
continue
}
if (customerChoice == customers.size + 1) {
continueShopping = false
continue
}
val currentCustomer = customers[customerChoice - 1]
currentCustomer.displayCustomerInfo()
VendingMachine.displaySnacks()
println("Enter snack number to purchase or 0 to cancel:")
val snackChoice = readLine()?.toIntOrNull()
if (snackChoice == null || snackChoice !in 0..VendingMachine.snacksInventory.size) {
println("Invalid choice. Try again.")
continue
}
if (snackChoice == 0) {
println("Purchase cancelled.")
continue
}
VendingMachine.purchaseSnack(currentCustomer, snackChoice - 1)
}
// Final report
VendingMachine.report()
customers.forEach { it.displayCustomerInfo() }
println("Thank you for using the Kotlin Vending Machine. Goodbye!")
}