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

Java Swing图形计算项目中equals类型不匹配导致运行异常问题

问题分析与修复方案

核心问题

你遇到的IDE警告和运行异常根源是错误地用数组对象和字符串做相等比较:

  • choices是String[]类型的数组,而"Area"/"Volume"是String类型,不同类型对象用equals()比较永远返回false,这就是后续图形选择面板无法触发的原因。
  • 真正需要判断的是下拉菜单的返回值question,这个变量才存储了用户选中的选项。

修复后的代码

import javax.swing.JOptionPane;
public class Shapes 
{
    public static void main(String[] args)
    {
        // Dropdown menu for area and volume
        String[] choices = {"Area", "Volume"};
        String question = (String) JOptionPane.showInputDialog(null, "What would you like to calculate?",
            "Shapes", JOptionPane.QUESTION_MESSAGE, null,
            choices,
            choices[0]);
        
        // 处理用户取消选择的情况,避免空指针异常
        if (question == null) {
            return;
        }
        
        System.out.println(question);

        if (question.equals("Area"))
        {
            // user chooses area
            String[] choices2D = {"triangle", "parallelogram", "rectangle", "trapezoid", "circle"};
            String question2D = (String) JOptionPane.showInputDialog(null, "What shape will you choose?",
                "Shapes", JOptionPane.QUESTION_MESSAGE, null,
                choices2D,
                choices2D[0]);
            System.out.println(question2D);
        }
        // user chooses volume
        if (question.equals("Volume"))
        {
            String[] choices3D = {"cone", "cylinder", "rectanglular prism", "trapezoid prism", "sphere"};
            String question3D = (String) JOptionPane.showInputDialog(null, "What figure will you choose?",
                "Shapes", JOptionPane.QUESTION_MESSAGE, null,
                choices3D,
                choices3D[0]);
            System.out.println(question3D);
        }
    }
}

额外优化建议

  • 可以用equalsIgnoreCase()替代equals(),让判断不区分大小写,提升用户体验。
  • 后续可把图形计算逻辑封装成独立方法,让代码结构更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:50:20