LearnFrenzy
Sign in Take a free test

Records, Enums and Sealed Classes · Records, Enums and Sealed Programs · Question 1

Vending machine with an enum of products in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

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.

Solution
Main.java
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));
    }
}

Output Verified by compiling and running

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.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links