簡體   English   中英

如何檢查數字是否適合Java中的原始類型?

[英]How to check if number fits primitive type in java?


我需要進行一些輸入驗證,但遇到一個問題,而且我似乎也找不到答案(即使使用Google)。 問題很簡單:我在輸入中有2個正整數,我需要檢查它們的乘積是否適合Java中的int類型。
我的嘗試之一是將乘積與Integer.MAX_VALUE進行比較,但是如果乘積對於整數而言太大,則值將變為負數。 我想通過符號變化來推斷產品太大,但是似乎如果產品“太大”,它將再次變得積極。
有人可以建議我如何檢測數字是否太大嗎?
提前謝謝了!

如果您正在執行UI,那么大概不會特別着急。 因此,您可以使用BigInteger,然后針對MAX_VALUE測試產品。

將值強制轉換為int ,看值是否相同。 一個簡單的檢查看起來像

double d =
long l =
BigInteger bi = 

if (d == (int) d) // can be represented as an int.
if (l == (int) l) // can be represented as an int.

int i = bi.intValue();
if (bi.equals(BigInteger.valueOf(i)))

如果在回滾時該值相同,則不會丟失任何信息,您可以使用int值。

搜索並找到以下內容

Java在溢出方面比較謹慎。 沒有編譯時警告或運行時異常可讓您知道計算結果何時變得太大而無法存儲回int或long中。 也不存在浮動或雙重溢出的警告。

/**
 * multiplies the two parameters, throwing a MyOverflowException if the result is not an int.
 * @param a multiplier
 * @param b multiplicand
 * @result product
 */
public static int multSafe(int a, int b) throws MyOverflowException
{
   long result = (long)a * (long)b;
   int desiredhibits = - ((int)( result >>> 31 ) & 1);
   int actualhibits = (int)( result >>> 32 );
   if ( desiredhibits == actualhibits )
   {
      return(int)result;
   }
   else
   {
      throw new MyOverflowException( a + " * " + b + " = " + result );
   }
}

您可以根據輸入值創建一個BigInteger並使用其intValue()方法進行轉換。 如果BigInteger太大而無法容納int,則僅返回低階32位。 因此,您需要將結果值與輸入值進行比較,以確保它不會被截斷。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM