Java: Integer from String or default Integer as Result
Question by Guest | 2016-08-05 at 19:46
I would like to extract an integer value from some user input. The user input is in string format, but I want to convert it so that the input is available as integer.
Because I do not know whether the user has indeed typed a real number into the input field, I am searching for a function that can do the following: if the passed string is the correct number, I would like to get this string as number. Otherwise, I want to get a specified default value. Is there some function available for that?
Related Topics
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
Android Programming: Receive Responce from HTTP POST Request
Tutorial | 0 Comments
Java: Smaller/Larger Comparison of Strings - The operator > is undefined for the argument type(s) java.lang.String
Question | 1 Answer
Java: Case Insensitive Equals - String Comparison
Info | 0 Comments
Android Getting Sound Levels
Open Question | 1 Answer
Java: Split at point str.split(".") does not work
Question | 1 Answer
Java: Keep empty fields in Split-Array
Tip | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
Of course, you can quickly write such a function on your own. It can look like the following (the first parameter is the string, the second parameter is the default integer):
Calling the function can be done like that:
The first line in this example converts the string "123" to the number 123. In the second line, we are passing the string "ABC" so that we get the specified default value 0 as a result.
By the way, we are using the line StringUtils.trim(value) in our function. With this, we are cutting off possible whitespace from the beginning and the end of the string before converting. The third line in our example is demonstrating that.
2016-08-05 at 22:07