0

I'm a Vietnamese so my English's not good, please sympathize me. Thanks in advance. I have a question. I input a integer value but if it would been out of the size of int. Ex: I input a = 1323544875154846543513521 So how to catch the error? I must input in and then check the value?

Diao Vũ
  • 109
  • 10

2 Answers2

0

Simple: don't use int, use Use BigInteger.

You might also wanna look other JVM languages that have number auto-casting, that is, automatically changing the number type according to the value at runtime (e.g. Clojure).

m0skit0
  • 25,268
  • 11
  • 79
  • 127
0

I input a integer value but if it would been out of the size of int. Ex: I input a = 1323544875154846543513521 So how to catch the error?

System.out.println(Integer.MAX_VALUE+1); // anymore than the max will wrap around, value printed = -2147483648
System.out.println(Integer.MIN_VALUE-1); // if less than the min it will also wrap around, value printed = 2147483647

you could use Math.toIntExact(long value) if you want to receive an exception on overflow/underflow.

Alternatively, you could use BigInteger or BigDecimal which have no limit in size (your RAM is the limit).

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126