1. 自動販賣機設計

namespace Q1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int[] price = new int[] { 35, 30, 25, 30 };
        string[] name = new string[] { "Cola", "PEPSO", "Diet Pepso", "Diet Cola" };
        void handle(int i)
        {
            int p = price[i];
            string n = name[i];
            if (balance < p)
            {
                return;
            }

            balance -= p;
            bal();

            old += " 送出 " + n;
            system.Text = old;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            handle(0);
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            handle(1);
        }

        private void pictureBox3_Click(object sender, EventArgs e)
        {
            handle(2);
        }

        private void pictureBox4_Click(object sender, EventArgs e)
        {
            handle(3);
        }

        int balance = 0;
        private void button1_Click(object sender, EventArgs e)
        {
            int[] amt = new int[] { 5, 10, 50 };
            List<RadioButton> list = new List<RadioButton>(new[] { radioButton1, radioButton2, radioButton3 });
            for (int i = 0; i < list.Count; i++)
            {
                RadioButton? item = list[i];
                if (item.Checked)
                {
                    balance += amt[i];
                    bal();
                }
            }
        }

        void bal()
        {
            textBox1.Text = $"{balance:0.0}";
        }

        string old = "";

        private void button2_Click(object sender, EventArgs e)
        {
            if (balance == 0)
            {
                old = "";
                system.Text = "";
                return;
            }
            old += $" 已退還 {balance} 元";
            system.Text = old;
            balance = 0;
            bal();
        }
    }
}

Last updated