Model products as an enum with code, name and price; process purchase requests by code with inserted money, printing the product and change, or an error.
import java.util.Arrays;
import java.util.Optional;
enum Product {
A1("Water", 20), A2("Juice", 45), B1("Chips", 30), B2("Chocolate", 60);
final String label;
final int price;
Product(String label, int price) { this.label = label; this.price = price; }
static Optional<Product> byCode(String code) {
return Arrays.stream(values()).filter(p -> p.name().equalsIgnoreCase(code)).findFirst();
}
}
public class Main {
static String buy(String code, int paid) {
return Product.byCode(code)
.map(p -> paid < p.price ? "insert Rs " + (p.price - paid) + " more for " + p.label
: p.label + " dispensed, change Rs " + (paid - p.price))
.orElse("invalid code " + code);
}
public static void main(String[] args) {
System.out.println(buy("A2", 50));
System.out.println(buy("b2", 50));
System.out.println(buy("C9", 100));
System.out.println(buy("B1", 30));
}
}
Juice dispensed, change Rs 5 insert Rs 10 more for Chocolate invalid code C9 Chips dispensed, change Rs 0
The enum is the product catalogue; a static lookup returns an Optional instead of throwing like valueOf.