Using optional to handle string-to-digital problems in Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.