简体   繁体   中英

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

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. 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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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