Get text from textfield
81,598
Solution 1
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);
Solution 2
use String.valueOf() instead of Double.parseDouble() this will help you convert double into string value
Author by
Ralph Lorenz
Updated on July 09, 2022Comments
-
Ralph Lorenz almost 2 years
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?