Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text from textfield

I'm making a GUI program. In my first program I have the following code:

double num1;
num1 = Double.parseDouble(guess.getText());

I believe that this code gets the value from the text field and converts it to double.

How can I get the value and convert it to String or Char?


1 Answers

Since the getText() already returns a String, storing its value as a String is trivial.

In order to parse a double, you've already done it, just watch for the NumberFormatException, in case of invalid input.

To store its value as a char, that depends on your requirements. Do you want the first character? Do you require the string to have only a single character? Is any character valid? And so on.

// Storing the value as a String.
String value = guess.getText();

// Storing the value as a double.
double doubleValue;
try {
    doubleValue = Double.parseDouble(value);
} catch (NumberFormatException e) {
    // Invalid double String.
}

// Storing the value as a char.
char firstChar = value.length() > 0 ? value.charAt(0) : (char) 0;

// Require the String to have exactly one character.
if (value.length() != 1) {
    // Error state.
}
char charValue = value.charAt(0);
like image 200
afsantos Avatar answered Jan 22 '26 10:01

afsantos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!