Programming A Vending Machine

Sungju Kim·2024년 7월 4일

What does the program do?

  • displays the menu (available beverages and their prices)
  • takes the user's keyboard input for the menu and displays the price
  • takes the user's input for the money they have inserted into the machine
  • calculates the change and alerts the user if the money is insufficient

Notable features of Java used

  • map
    • how to construct a map
    • how to call entries in a for-loop
    • how to check if a key exists in a map
    • how to get the value with a key in a map
  • scanner
    • getting user input
    • closing the keyboard
  • type-casting

    int insertedMoney = Integer.parseInt(insertedAmount);


import java.util.Map;
import java.util.Scanner;

public class level_2 {
	public static void main(String[] args) {
		Map<String, Integer> beverages = Map.of(
                "사이다", 1700,
                "콜라", 1900,
                "식혜", 2500,
                "솔의눈", 3000
        );
		
		// the for-loop below goes over each entryset in the map entry
		for (Map.Entry<String, Integer> entry : beverages.entrySet()) {
            System.out.printf("%-3s : %,6d원\n", entry.getKey(), entry.getValue());
        }

		Scanner menu = new Scanner(System.in);
		String userChoice = menu.nextLine();

		if (!beverages.containsKey(userChoice)) {
            System.out.println("'" + userChoice + "' 은/는 메뉴에 없습니다");
        } else {
            payForDrink(userChoice, beverages);
        }
		menu.close();
	}
	public static void payForDrink(String drink, Map<String, Integer> beverages) {
		// int priceOfDrink = beverages.get(drink);
		System.out.println("선택하신 음료의 가격은 " + beverages.get(drink) + "원 입니다.");
		
		System.out.println("투입 숫자로 금액을 적어주십시오:");
		Scanner money = new Scanner(System.in);
		String insertedAmount = money.nextLine();
		System.out.println("투입하신 금액은: " + insertedAmount + "원 입니다");
		
		int insertedMoney = Integer.parseInt(insertedAmount);
		if (insertedMoney >= beverages.get(drink)) 
		{
			int change = insertedMoney - beverages.get(drink);
			System.out.println("음료를 가져가싶시오, 고객님의 잔액은 " + change + "원 입니다.");
		}
		else 
		{
			System.out.println("돈 부족합니다");
		}
		money.close();
	}
}
profile
Fully ✨committed✨ developer, always eager to learn!

0개의 댓글