Treat empty field even containing spaces

Asked

Viewed 160 times

2

I made a Celsius temperature converter for Fahrenheit, I’m willing to treat if in JTextField is different from 0, display the temperature in Fahrenheit, but appears 0.0 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));
            }
        }

1 answer

2


If the intention is not to let validate if the String is empty or with spaces only, try applying trim() to remove blanks:

@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));


   }

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

  • What is the use here || fieldText.equals("0") ?

  • @user67285 validation is not empty and be non-zero ne? this is valid if the reported value is zero. I made a correction, it should be different from zero.

  • It was just the spaces.

  • @user67285 good, then I have sinned by the excess :D just remove this validation that will work right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.