1

I wrote a very basic Fahrenheit to Celsius converter just for practice and it seems to be working but I'd like to include some code that would tell the user to "Enter a valid number" if they either add a String or nothing. I'm assuming that I need an if statement to check if the value is == to double like it's supposed to be I'm not sure how to do this. Everything I try gives me some kind of error and the variable "value" is always underlined with a red squiggly.

Here's what I have:

package sample;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;

public class Controller {

    @FXML
    private TextField textBoxC;

    @FXML
    private Button btnCels;

    @FXML
    private TextField textBoxF;

    @FXML
    void btnCels_onAction(ActionEvent event) {

                  double value = Double.parseDouble(textBoxF.getText());
                  double answer = value * 9 / 5 + 35;
                  textBoxC.setText(String.valueOf(answer));

      }
}

What could I add to this code to make it run ONLY if the value in textBoxF was a valid double data type?

Thank you very much.

  • Check the following post: http://stackoverflow.com/questions/12361492/java-typeof-primitive-data-types.. – nbro Aug 05 '15 at 22:30

2 Answers2

2

I suppose you do want to work around the Exception you get when trying to parse the string to a double?

Simple workaround (not smooth but it works):

try{
    double value = Double.parseDouble(textBoxF.getText());
    double answer = value * 9 / 5 + 35;
              textBoxC.setText(String.valueOf(answer));
}
catch (Exception e){
//What should happen when the input string is no double?
}

More Information

This way you catch the exception thrown. Still, you will always try to convert but you will not always set the new text in the textbox.

Community
  • 1
  • 1
Leon Bohmann
  • 402
  • 1
  • 4
  • 16
1

parseDouble throws NumberFormatException if String parameter can't be converted to Double. You can catch it and do what you want:

try {
    double value = Double.parseDouble(textBoxF.getText());
    double answer = value * 9 / 5 + 35;
    textBoxC.setText(String.valueOf(answer));
} catch (NumberFormatException e) {
     // here provide your logic to tell the user to "Enter a valid number" 
}
ka4eli
  • 5,294
  • 3
  • 23
  • 43