2017-04-07 44 views
0

我是越南人,所以我的英語不好,請同情我。提前致謝。 我有一個問題。 我輸入一個整數值,但是如果它超出了int的大小。 例如:I input a = 1323544875154846543513521 那麼如何捕捉錯誤呢? 我必須輸入,然後檢查值?超過整數大小的值

回答

0

簡單:不要使用int,請使用使用BigInteger

您可能還想看看其他的具有數字自動轉換功能的JVM語言,即根據運行時的值(例如Clojure)自動更改數字類型。

0

我輸入一個整數值,但是如果它超出了int的大小。 例如:我輸入a = 1323544875154846543513521那麼如何捕捉錯誤?

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 

你可以使用Math.toIntExact(long value)如果您希望收到溢/下溢異常。

或者,您可以使用BigIntegerBigDecimal,它們的大小沒有限制(您的RAM是限制)。