You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWT Choice组件在计算器中的问题:如何传递选中运算符参与计算

AWT计算器:根据Choice选中的运算符执行计算

首先,你需要先确保已经正确初始化并添加了Choice控件的运算选项,示例代码如下:

// 初始化Choice并添加运算符选项
Choice operatorChoice = new Choice();
operatorChoice.add("+");
operatorChoice.add("-");
operatorChoice.add("*");
operatorChoice.add("/");
// 将Choice添加到你的AWT容器中(比如Frame)
yourFrame.add(operatorChoice);

接下来,在Calculate按钮的事件处理逻辑里,先获取Choice选中的运算符,再通过分支判断执行对应运算,同时处理可能的异常(比如除零错误):

Double result = 0.0;

if (e.getSource() == b1) {
    try {
        Double n1 = Double.parseDouble(t1.getText());
        Double n2 = Double.parseDouble(t2.getText());
        
        // 获取Choice选中的运算符
        String selectedOperator = operatorChoice.getSelectedItem();
        
        // 根据运算符执行对应计算
        switch(selectedOperator) {
            case "+":
                result = n1 + n2;
                break;
            case "-":
                result = n1 - n2;
                break;
            case "*":
                result = n1 * n2;
                break;
            case "/":
                // 处理除零异常
                if(n2 != 0) {
                    result = n1 / n2;
                } else {
                    t3.setText("Error: Divide by zero");
                    return; // 直接返回,不执行后续赋值
                }
                break;
            default:
                t3.setText("Invalid operator");
                return;
        }
        
        // 将计算结果设置到t3输入框
        t3.setText(String.valueOf(result));
    } catch(NumberFormatException ex) {
        t3.setText("Please enter valid numbers");
    }
}

关键说明

  • 通过operatorChoice.getSelectedItem()可以直接获取当前选中的运算符字符串
  • 使用switch分支比多个if-else更清晰,适合处理固定的运算符选项
  • 添加了try-catch块处理非数字输入的异常,避免程序崩溃
  • 针对除法单独做了除零判断,防止运行时抛出算术异常

内容的提问来源于stack exchange,提问作者Duka Bzooka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 17:45:50