코드 - 자판기

포키·2022년 10월 19일
0

국비과정

목록 보기
73/73
public class Test {
	public static void main(String[] args)	{
		VendingMachine v = new VendingMachine();
		v.printInfo();
		v.putIn(3000);
		v.putIn(-1000);
		v.buy(1);
		v.buy(2);
		v.buy(3);
		v.buy(4);
		v.buy(5);
		v.buy(6);
		v.returnChange();
	}
}
class VendingMachine {
	// Variable balance
	private int balance = 0;
	// Variable item prices
	private int coffee;
	private int water;
	private int cookies;
	private int snack;
	private int candy;
    // variable item number
    // private int num;
	
	// Constructor
	public VendingMachine(){
		coffee = 1200;
		water = 600;
		cookies = 1000;
		snack = 1500;
		candy = 300;
	}
	// itemInfo method
	public void printInfo(){
		System.out.println("===========<Menu>===========");
		System.out.printf("\t1. coffee : %d\n\t2. water : %d\n\t3. cookies : %d\n\t4. snack : %d\n\t5. candy : %d\n",coffee,water,cookies,snack,candy);
		System.out.println("============================");
	}
	// deposit method
	public void putIn(int cash){
		if(cash > 0){
			balance += cash;
			printBalance();
		} else {
			System.out.println("Please enter positive number.");
		}
	}
    // buying method
    public String buy(int num){
        if(validNum(num)){
            if(enoughMoney(num)){
                itemOut(num);
            }
        }
        return null;
    }

	// if the number is vaild return true, if not do false
	private boolean validNum(int num){
	    switch (num){
	       case 1 :
	       case 2 :
	       case 3 :
	       case 4 :
	       case 5 :
	           return true;
	       default :
	           System.out.println("invaild number");
	           return false;
	    }
	}
	// if money is enough then pay for the item, if not then print "short of money"
	private boolean enoughMoney(int num){
	    int price = 0;
	    switch (num){
	       case 1 :
	            price = coffee;
	            break;
	       case 2 :
	            price = water;
	            break;
	       case 3 :
	            price = cookies;
	            break;
	       case 4 :
	           price = snack;
	           break;
	       case 5 :
	           price = candy;
	           break;
	    }
	    if(balance >= price){
	        balance -= price;
	        return true;
	    } else {
	        System.out.println("short of money.");
	        return false;
	    }
	}
	
	private String itemOut(int num){
		String result = null;
		switch (num) {
			case 1 : 
				result = "coffee";
				break;
			case 2 :
				result = "water";
				break;
			case 3 :
				result = "cookies";
				break;
			case 4 :
				result = "snack";
				break;
			case 5 : 
				result = "candy";
				break;
		}
		printBalance();
        return result;
	}
	// returnChange method
	public int returnChange() {
		int change = balance;
		balance = 0;
		printBalance();
		return change;
	}
	// show balance method
	public void printBalance() {
		System.out.println("balance : " + balance);
	}
}
profile
welcome

0개의 댓글