In the recent development of JavaFX, because there is no control that can only enter a number, each time the user input string is converted, but Java in the use of the Double.parsedouble () method when the conversion fails to throw an exception, every time try, Catch is tedious, and I learned swift in my spare time to find that Swift's optional and as can be extremely elegant solutions to this problem, the conversion succeeds to get the value, the failure is nil (null in Java), and Java8 introduces the optional class, So I tried to encapsulate it, the code is as follows:
Public class Stringutil { publicstatic optional<double> todouble (String s) { Try { return optional.of (double.parsedouble (s)); } Catch (Exception e) { return optional.empty ();}} }
This way, for example, when a user is required to enter a number, such as a student's score, this is the only way to write:
New Student (); Stringutil.todouble (Gradefield.gettext ()). Ifpresent (Grade->student.setgrade (grade));
The personal feeling is still relatively concise.
Using optional to handle string-to-digital problems in Java