00 Votes

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?

ReplyPositiveNegative
0Best Answer0 Votes

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):

public static int parseIntOrDefault(String value, int defaultValue) {
  int result = defaultValue;
  string s = StringUtils.trim(value);
  try {
    result = Integer.parseInt(s);
  } catch (Exception e) { }
  return result;
}

Calling the function can be done like that:

int i = parseIntOrDefault("123", 0));   // 123
int i = parseIntOrDefault("ABC", 0));   // 0
int i = parseIntOrDefault(" 1 ", 0));   // 1

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

ReplyPositive Negative
Reply

Related Topics

Android Getting Sound Levels

Open Question | 1 Answer

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.