Software Test week fourth--string to int

Source: Internet
Author: User

There are two common methods of string to int in Java:

The first method: I=integer.parseint (str);
The second method: I=integer.valueof (str). Intvalue ();

Both of these methods can implement string to int, but there is a difference between the two, the first method directly uses the string type of static method, the second method will produce more than one object. But both will throw an exception.

Here's a look at using parseint (str), when STR is not a number, throw an exception solution:

First, wrap the parseint () with a try catch, accept the exception information yourself, and implement the solution.

e.g.

     try{

Integer i = integer.parseint (str);

}

catch (Exception e)

{

SYSTEM.OUT.PRINTLN ("Transition Failure")

}

  Second, use regular expressions to filter
e.g.






}



The Third Kind: write the function, judge the string, call the Jave's own judgment whether it is a function of the number, also can increase the readability
e.g.
for (int i = 0; i < str.length (); i++) {
if (!character.isdigit (Str.charat (i))) {
return false;
}
}

Finally, sometimes reading a string is necessary to remove the front and back space, or throw an exception, this time we use the String.Trim ("") function can be used to remove the first end of the string blank.

Software Test week fourth--string to int

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.