2025.3.24(周一)

自动售货机代码:

package drinks;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Drinks {
    public static void main(String[] args) {
        // 创建主窗口
        JFrame frame = new JFrame("自动售货机系统");
        frame.setSize(400, 250);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null);

        // 创建投币金额标签和下拉框
        JLabel labelCoin = new JLabel("请选择投币金额:");
        labelCoin.setBounds(50, 30, 120, 25);
        frame.add(labelCoin);

        String[] coins = {"请选择", "1元", "五角"};
        JComboBox<String> comboCoin = new JComboBox<>(coins);
        comboCoin.setBounds(180, 30, 150, 25);
        frame.add(comboCoin);

        // 创建商品选择标签和下拉框
        JLabel labelProduct = new JLabel("请选择商品:");
        labelProduct.setBounds(50, 70, 120, 25);
        frame.add(labelProduct);

        String[] products = {"请选择", "啤酒", "橙汁"};
        JComboBox<String> comboProduct = new JComboBox<>(products);
        comboProduct.setBounds(180, 70, 150, 25);
        frame.add(comboProduct);

        // 结果显示标签
        JLabel resultLabel = new JLabel("");
        resultLabel.setBounds(50, 150, 300, 25);
        frame.add(resultLabel);

        // 创建按钮
        JButton button = new JButton("购买商品");
        button.setBounds(150, 110, 120, 30);
        frame.add(button);

        // 按钮点击事件
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int button1 = comboCoin.getSelectedIndex();  // 投币金额
                int button2 = comboProduct.getSelectedIndex();  // 商品选择

                // 验证输入
                if (button1 == 0 || button2 == 0) {
                    resultLabel.setText("❌ 请选择投币金额和商品!");
                    return;
                }

                // 处理逻辑
                String result = getDrink(button1, button2);
                resultLabel.setText("✅ " + result);
            }
        });

        // 显示窗口
        frame.setVisible(true);
    }

    // 计算取货或找零
    public static String getDrink(int button1, int button2) {
        if (button1 == 2 && button2 == 1) {
            return "请取走您的啤酒";
        } else if (button1 == 2 && button2 == 2) {
            return "请取走您的橙汁";
        } else if (button1 == 1 && button2 == 1) {
            return "请取走您的啤酒,将找零五角";
        } else if (button1 == 1 && button2 == 2) {
            return "请取走您的橙汁,将找零五角";
        } else {
            return "❌ 输入无效!";
        }
    }
}

 

posted @ 2025-03-23 09:33  记得关月亮  阅读(8)  评论(0)    收藏  举报