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

Java租金收益率程序用户输入不生效及NumberFormatException问题排查

问题分析与解决方案

你的代码存在两个核心问题:

  • 计算时机错误:你在组件刚初始化时就直接读取JTextField的初始值并解析计算,这时候用户还没机会输入内容。后续用户修改文本框内容后,程序不会自动重新执行计算逻辑,所以始终用的是初始的0.1和1.2。
  • 未处理数字格式异常:Double.parseDouble()方法在遇到非数字字符串时会直接抛出NumberFormatException,你没有添加任何异常捕获逻辑,一旦输入非数字内容就会导致程序崩溃。

修正方案示例:

1. 添加触发计算的交互(比如按钮点击)

把计算逻辑放到按钮的点击事件里,只有当用户输入完成后点击按钮,才读取文本框内容并计算:

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

public class RentalYieldCalculator {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Rental Yield Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));

        JLabel label1 = new JLabel("Annual Rental Income");
        JTextField textf1 = new JTextField("0.1", 16);
        JLabel label2 = new JLabel("Purchased Price");
        JTextField textf2 = new JTextField("1.2", 16);
        JButton calculateBtn = new JButton("Calculate Yield");
        JLabel resultLabel = new JLabel("Yield: ");

        // 给按钮添加点击事件监听器
        calculateBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    // 在按钮点击时才读取用户输入并解析
                    double annualRent = Double.parseDouble(textf1.getText());
                    double purchasePrice = Double.parseDouble(textf2.getText());
                    
                    // 避免除以0的情况
                    if (purchasePrice <= 0) {
                        resultLabel.setText("Error: Purchase price must be greater than 0");
                        return;
                    }
                    
                    double yield = (annualRent / purchasePrice) * 100;
                    resultLabel.setText(String.format("Yield: %.2f%%", yield));
                } catch (NumberFormatException ex) {
                    // 捕获非数字输入的异常,提示用户
                    resultLabel.setText("Error: Please enter valid numbers");
                }
            }
        });

        frame.add(label1);
        frame.add(textf1);
        frame.add(label2);
        frame.add(textf2);
        frame.add(calculateBtn);
        frame.add(resultLabel);
        frame.pack();
        frame.setVisible(true);
    }
}

2. 关键优化点说明:

  • 延迟计算时机:将数值解析和计算逻辑移到按钮点击事件中,确保读取的是用户输入后的内容。
  • 异常捕获:用try-catch包裹Double.parseDouble(),捕获NumberFormatException,并给用户友好的错误提示。
  • 边界判断:增加了对购买价格为0或负数的判断,避免出现除以0的算术异常。

内容的提问来源于stack exchange,提问作者Sai Aung Zaw Oo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 02:57:51