【问题标题】:How to check if number fits primitive type in java?如何检查数字是否适合java中的原始类型?
【发布时间】:2011-02-06 19:45:18
【问题描述】:


我需要做一些输入验证,但遇到了一个问题,我似乎没有找到答案(即使是谷歌)。问题很简单:我的输入有 2 个正整数,我需要检查它们的乘积是否适合 Java 中的 int 类型。
我的尝试之一是将产品与 Integer.MAX_VALUE 进行比较,但似乎如果产品对于整数来说太大,值就会变为负数。 我想通过符号变化来推断产品太大,但似乎如果产品“太大”,它会再次变得积极。
有人可以告诉我如何检测数字是否变得太大?
非常感谢!

【问题讨论】:

标签: java integer


【解决方案1】:

如果你正在做一个 UI,你可能并不特别着急。因此,您可以使用 BigInteger,然后针对 MAX_VALUE 测试产品。

【讨论】:

    【解决方案2】:

    将值转换为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 值。

    【讨论】:

      【解决方案3】:

      搜索并found the following:

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

      【讨论】:

        【解决方案4】:

        您可以从您的输入值创建一个BigInteger 并使用它的 intValue() 方法进行转换。如果 BigInteger 太大而无法放入 int,则仅返回低 32 位。因此,您需要将结果值与输入值进行比较,以确保它没有被截断。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-06
          • 1970-01-01
          • 2011-02-08
          • 1970-01-01
          • 1970-01-01
          • 2021-10-07
          • 2012-01-15
          • 2017-07-18
          相关资源
          最近更新 更多