自動售貨機

import java.util.Scanner;
/**
 * 華爲機試 自動售貨機
 * 不知道對錯
 * @author qxl
 *
 */
public class Shop {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int price1 = 2, s_count1 = 5;
		int price2 = 3, s_count2 = 10;
		int price3 = 4, s_count3 = 14;//初始化
		int y_count1 = 5;
		int y_count2 = 5;
		int y_count5 = 3;
		while (sc.hasNext()) {
			String s = sc.nextLine();//p 5,p 5,p 5,b A3,b A3,b A2
			s = s.replace(" ", ",");//p,5,p,5,p,5,b,A3,b,A3,b,A2
			String[]str = s.split(",");//{"p","5","p","5","p","5","b","A3","b","A3","b","A2"}
			int total_pay = 0;
			int total_cost = 0;
			for(int i=0;i<str.length;i+=2){
				if(str[i].equals("p")){
					total_pay+=Integer.parseInt(str[i+1]);
				}
				if(str[i].equals("b")){
					if(str[i+1].equals("A1")){
						total_cost+=price1;
						s_count1--;
					}
					if(str[i+1].equals("A2")){
						total_cost+=price2;
						s_count2--;
					}
					if(str[i+1].equals("A3")){
						total_cost+=price3;
						s_count3--;
					}
				}
			}
			int remain = total_pay - total_cost;//找錢
			int i5=0,i2=0,i1=0;//分別找五、二、1元錢的張數
			i5 = remain/5;
			if(i5<y_count5){
				remain = remain-i5*5;
			}else{
				remain = remain-y_count5*5;
			}
			if(remain!=0){
				i2 = remain/2;
				if(i2<y_count2){
					remain = remain - i2*2;
				}else{
					remain = remain - y_count2*2;
				}
			}
			if(remain!=0){
				i1 = remain/1;//不考慮非法輸入,必定能找零。
			}
			int lost_count1 = y_count1 - i1;//存錢盒中剩餘1塊錢的數量
			int lost_count2 = y_count2 - i2;//存錢盒中剩餘2塊錢的數量
			int lost_count5 = y_count5 - i5;//存錢盒中剩餘5塊錢的數量
			String s1 = "A1" + " " + s_count1 + ",";
			String s2 = "A2" + " " + s_count2 + ",";
			String s3 = "A3" + " " + s_count3 + ",";
			String s4 = "1" + " " + lost_count1 + ",";
			String s5 = "2" + " " + lost_count2 + ",";
			String s6 = "5" + " " + lost_count5;
			
			System.out.println(s1+s2+s3+s4+s5+s6);
		}
	}
}
相關文章
相關標籤/搜索