简体   繁体   English

如何检查数字是否适合Java中的原始类型?

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


I need do to some input validation but run into a question and I do not seem to find an answer (even with Google). 我需要进行一些输入验证,但遇到一个问题,而且我似乎也找不到答案(即使使用Google)。 The problem is simple: I have 2 positive integers on the input, and I need to check if their product fits int type in Java. 问题很简单:我在输入中有2个正整数,我需要检查它们的乘积是否适合Java中的int类型。
One of my attempts was to compare product with Integer.MAX_VALUE, but it seems if the product is too big for integer, value becomes negative. 我的尝试之一是将乘积与Integer.MAX_VALUE进行比较,但是如果乘积对于整数而言太大,则值将变为负数。 I wanted to reason that product is too big by change in sign, but it seems if the product is "way too big" it will become positive again. 我想通过符号变化来推断产品太大,但是似乎如果产品“太大”,它将再次变得积极。
Could someone advise me how to detect if number becomes too big? 有人可以建议我如何检测数字是否太大吗?
Many thanks in advance! 提前谢谢了!

If you are doing a UI, you are presumably in no particular hurry. 如果您正在执行UI,那么大概不会特别着急。 So you could use a BigInteger and then test the product against MAX_VALUE. 因此,您可以使用BigInteger,然后针对MAX_VALUE测试产品。

Cast the value to int and see if the value is the same. 将值强制转换为int ,看值是否相同。 A simple check looks like 一个简单的检查看起来像

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

If the value is the same when cast back, there is no loss of information and you can use an int value. 如果在回滚时该值相同,则不会丢失任何信息,您可以使用int值。

Searched and found the following : 搜索并找到以下内容

Java is cavalier about overflow. Java在溢出方面比较谨慎。 There are no compile-time warnings or run-time exceptions to let you know when your calculations have become too big to store back in an int or long. 没有编译时警告或运行时异常可让您知道计算结果何时变得太大而无法存储回int或long中。 There is no warning for float or double overflow either. 也不存在浮动或双重溢出的警告。

/**
 * 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 );
   }
}

You could create a BigInteger from your input value and use its intValue() method to convert. 您可以根据输入值创建一个BigInteger并使用其intValue()方法进行转换。 If the BigInteger is too big to fit in an int, only the low-order 32 bits are returned. 如果BigInteger太大而无法容纳int,则仅返回低阶32位。 So you need to compare the resulting value to your input value to ensure it was not truncated. 因此,您需要将结果值与输入值进行比较,以确保它不会被截断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM