Treat empty field even containing spaces

2

I made a temperature converter from Celsius to Fahrenheit, I'm trying to treat if the JTextField is different from 0, display the temperature in fahrenheit, but 0.0 appears until empty, with spaces inserted in that field.

@Override
    public void actionPerformed(ActionEvent e) {

        double resultado = 0, valor1;

        if(e.getSource() == btnOk) {
            if(!text1.getText().isEmpty()) {
               try {
                   valor1 = Double.parseDouble(text1.getText()); 
                   resultado = valor1 * 1.8 + 32;

                }catch(NumberFormatException e1) {}
                    text2.setText(String.valueOf(resultado));
            }
        }
    
asked by anonymous 19.02.2017 / 22:06

1 answer

2

If the intent is not to allow validation if the String is empty or has spaces only, try applying trim() to remove whitespaces:

@Override
    public void actionPerformed(ActionEvent e) {

        double resultado = 0, valor1;
        String fieldText = text1.getText().trim();

        if(e.getSource() == btnOk) {
            if(!fieldText.isEmpty()) {
               try {
                   valor1 = Double.parseDouble(fieldText); 
                   resultado = valor1 * 1.8 + 32;

                }catch(NumberFormatException e1) {}
                    text2.setText(String.valueOf(resultado));


   }
  

Note: trim () does not remove whitespace between the characters of the string, only those that are at the beginning and end. If a string is only passed with whitespace for this method, the result will be an empty string.

    
19.02.2017 / 22:11