如何获得两个jtextfield值的总和除以jtxtfield中的另一个jtxt值

时间:2017-09-08 23:52:11

标签: java mysql netbeans

我需要得到两个值并且除以一个值并在Jtxtfield中显示结果 我用这个代码

    {
    int num1,num2,num3,sum;
    num1=Integer.parseInt(PB_cash.getText());
    num2=Integer.parseInt(DC_cash.getText());
    num3=Integer.parseInt(BD_cash.getText());
    sum=num1+num2-num3;
    HB_cash.setText(" "+sum);
    }

我在没有数据库连接的情况下尝试了它并且运行良好 但是与数据库连接会产生运行时错误

这是错误

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: " 77000"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at bankapplication.Withdrawal_Interface.jButton7ActionPerformed(Withdrawal_Interface.java:758)
at bankapplication.Withdrawal_Interface.access$400(Withdrawal_Interface.java:30)
at bankapplication.Withdrawal_Interface$5.actionPerformed(Withdrawal_Interface.java:502)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6290)

Plz帮助我解决这个问题 感谢

1 个答案:

答案 0 :(得分:1)

查看收到的异常,您不能将字符串数值中的空格发送到: Integer.parseInt()方法:

您的例外:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: " 77000"

使用String.trim()方法删除制表符和空格:

{
    int num1,num2,num3,sum;
    num1=Integer.parseInt(PB_cash.getText().trim());
    num2=Integer.parseInt(DC_cash.getText().trim());
    num3=Integer.parseInt(BD_cash.getText().trim());
    sum=num1+num2-num3;
    HB_cash.setText(" " + String.valueOf(sum)); //why you want the space is beyond me :)
}

另一方面,看看你的JTextField名称,看起来实际上最终还是提供了现金。请考虑使用 float double 数据类型而不是 int 。这样,您还可以提供带小数的货币值,例如:5.99

相关问题