简体   繁体   English

无法将jTextfield字符串转换为浮点值…给数字格式异常

[英]Couldn't Convert jTextfield string into float value… Giving number format exception

Im experiencing a problem in parsing jTextfield into float value so i can perform operation but its giving number format exception 我在将jTextfield解析为float值时遇到问题,因此我可以执行操作,但是给定数字格式异常

Here is the Error 这是错误

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011)
    at java.lang.Float.parseFloat(Float.java:452) 

and this is what im doing 这就是我在做什么

float T1 = Float.parseFloat(txt_T1_f.getText());

You can add a check on the text value like this: 您可以像这样添加对文本值的检查:

String text = txt_T1_f.getText();
if (text != null && !text.isEmpty()) {
    float T1 = Float.parseFloat(text);
}

Before converting to float, check your string is not empty and not null. 在转换为float之前,请检查您的字符串不为空且不为null。 You are getting excepting since your string is empty. 由于字符串为空,您正在获得例外。

use 采用

  if(txt_T1_f.getText()!=null && !txt_T1_f.getText().isEmpty())
  float T1 = Float.parseFloat(txt_T1_f.getText());

First you should check your string to find out is it a float at all? 首先,您应该检查您的字符串以找出是否完全是浮点数? try this: 尝试这个:

    String regex="^([+-]?\\d*\\.?\\d*)$";
    String input = txt_T1_f.getText();
    float T1 ;
    if(Pattern.matches(regex, input)){
        T1 = Float.valueOf(input);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM