代码之家  ›  专栏  ›  技术社区  ›  Moustafa51

获取random.nextInt(argument)上的IllegalArgumentException错误

  •  -1
  • Moustafa51  · 技术社区  · 12 年前

    我在错误行中遇到非法ArgumentException。

          private final static int SPOT_DIAMETER=100;
          private int viewWidth;
    
          .
    
          .
    
          .
    
    
         @Override
          protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            // TODO Auto-generated method stub
          viewHeight=h;
          viewWidth=w;
    
         }
    

    “viewWidth-SPOT_DIAMETER”返回整数,不是吗?如何解决此错误?

        public void addNewSpot(){
    
    
    
       int x=random.nextInt(viewWidth-SPOT_DIAMETER);//error line
       .
    
       .
       .
        }
    
    3 回复  |  直到 12 年前
        1
  •  2
  •   JSlain    12 年前

    如Random.netint(int)所指定 JavaDoc ,如果你用负数调用它,你会得到这个异常,这可能就是发生的情况。

    Parameters:
    n - the bound on the random number to be returned. Must be positive.
    
    Returns:
    the next pseudorandom, uniformly distributed int value between 0 (inclusive) and n (exclusive) from this random number generator's sequence
    
    Throws:
    IllegalArgumentException - if n is not positive
    
        2
  •  0
  •   linuxedhorse    12 年前

    你确定你在写一个大于100的数字吗 SPOT_DIAMETER ),当您拨打 onSizeChanged() 方法检查它,因为正如JSlain已经说过的,当随机数发生器取负数时,会引发此异常。

    此外,可能您的方法不起作用/调用了 viewWidth 当您试图调用随机化器时,变量为空。

        3
  •  -1
  •   Jonathon Anderson    12 年前

    使用 viewWidth.SPOT_DIAMETER 假设它是公共常数。