0

Trying to run something like below will throw a NumberFormatException:

int i = Integer.parseInt("99999999999999999999999999999999999");

I want this to return Integer.MAX_VALUE instead such that:

int i = foobar("99999999999999999999999999999");
assert(i == Integer.MAX_VALUE);

What is the best way to accomplish this?

Layman
  • 797
  • 1
  • 7
  • 23

3 Answers3

2

You could use BigInteger

BigInteger bi = new BigInteger("99999999999999999999999999");
BigInteger mv = new BigInteger(String.valueOf(Integer.MAX_VALUE));
System.out.println(bi.compareTo(mv));

if (bi.compareTo(mv) > 0) 
    return Integer.MAX_VALUE;
else 
    return bi.intValue(); 
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • as per @DawoodsaysreinstateMonica comment below Elliots deleted answer, testing should also be done for large negative numbers too – Scary Wombat Nov 21 '19 at 06:03
1

You can try to parse the number using Integer.parseInt, if it fails, you try to parse it using Long.parseLong. Then you have two ways, if it fails, you try to parse using new BigInteger(stringVal), if it succeeds, you return MAX_INT. Then do the same using BigInteger.

You can't just return max_int if you got a NumberFormatException after attempting to parse it using Integer.parseInt because this exception can be thrown if the text is not a number (or contain characters with numbers).

Marwa Eldawy
  • 191
  • 2
  • 5
0
import java.util.regex.Pattern;

public class ForExample {

  public static void main(String[] args) {
    var strInt = "99999999999999999999999999999999999";

    //
    //
    int i = parseToInt(strInt);
    //
    //

    System.out.println(i == Integer.MAX_VALUE);
  }

  private static final Pattern PLUS_MINUS_ONLY_DIGITS = Pattern.compile("[+-]?\\d+");

  public static int parseToInt(String strInt) {
    try {
      return Integer.parseInt(strInt);
    } catch (NumberFormatException e) {
      if (PLUS_MINUS_ONLY_DIGITS.matcher(strInt).matches()) {
        return strInt.startsWith("-") ? Integer.MIN_VALUE : Integer.MAX_VALUE;
      }
      throw e;
    }
  }

}