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

JFrame开发BMI计算器时整数相加异常的解决方法

问题根源

你调用了错误的方法获取输入框内容:jt1.getHeight()是Swing组件的内置方法,作用是获取输入框组件本身的像素高度,你测试时返回固定值21,就是因为当前环境下JTextField默认像素高度为20,加1后刚好得到21,和你在输入框输入的内容完全无关。


需要修复的其他问题

  • BMI_Calculator类需要继承JFrame,否则无法直接调用setTitle、setVisible等窗口方法,类定义末尾多余的括号需要删除
  • JTextField拼写错误,你误写为JTextFeild
  • 按钮的ActionListener代码块末尾缺少分号
  • 获取输入框内容需要调用jt1.getText(),再将字符串转为整数类型,同时要做好空输入、非数字输入的异常捕获
  • 你当前的Get_BMI方法逻辑只是将输入值加1,和BMI计算逻辑无关,如果后续要实现真实BMI计算,还需要补充体重输入项,套用BMI=体重(kg)/(身高(m))²的公式

修正后的可运行代码

package com.company;

import javax.swing.*;

public class BMI_Calculator extends JFrame {
    JPanel jp = new JPanel();
    JLabel jl = new JLabel();
    JTextField jt1 = new JTextField(30);
    JButton jb = new JButton("Click here for BMI value");

    private BMI_Calculator() {
        setTitle("BMI_Calculator");
        setVisible(true);
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        jp.add(jt1);
        jt1.addActionListener(e -> {
            try {
                // 正确获取输入框内容并转为整数
                int Height_input = Integer.parseInt(jt1.getText().trim());
                jl.setText("Your height + 1:" + Get_BMI(Height_input));
            } catch (NumberFormatException ex) {
                jl.setText("请输入有效的数字");
            }
        });
        jp.add(jb);

        jb.addActionListener(e -> {
            try {
                int input = Integer.parseInt(jt1.getText().trim());
                jl.setText("Your height + 1:" + Get_BMI(input));
            } catch (NumberFormatException ex) {
                jl.setText("请输入有效的数字");
            }
        });
        jp.add(jl);
        add(jp);
    }

    private static int Get_BMI(int height) {
        // 你当前的逻辑是身高加1,后续可替换为真实BMI计算逻辑
        return height + 1;
    }

    public static void main(String[] args) {
        new BMI_Calculator();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 04:54:03