2014-09-02 15 views
-1

我在錯誤行上得到illegalArgumentException。在random.nextInt(參數)上獲取一個IllegalArgumentException錯誤

 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 
    . 

    . 
    . 
    } 

回答

2

正如Random.nextInt(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 
-1

使用viewWidth.SPOT_DIAMETER假設它是一個公共常數。

+0

我不明白如何使用viewWidth.SPOT_DIAMETER作爲公共常數我新對不起:( – Moustafa51 2014-09-02 22:38:11

+0

只是改變你的'''''' – NonSecwitter 2014-09-02 22:39:09

0

你確定你把一個數字,它更大,比100(你SPOT_DIAMETER),當你調用onSizeChanged()方法?檢查一下,因爲JSlain已經說過,當隨機數發生負數時這個異常會拋出。

此外,當您嘗試調用隨機程序時,也許您的方法無法正常工作/調用,並且您的viewWidth變量爲空。

+0

我知道變量viewWidth總是返回0因此random.nextInt(0 )給出異常,我正在尋找爲什麼getWidth()現在返回0? – Moustafa51 2014-09-02 23:40:39

+0

我不知道如何理解爲什麼getWidth()返回0如果我沒有看到你的代碼?)你有' random.nextInt(-100)',如果'viewWidth'包含0,不只是0。嘗試調試。 – linuxedhorse 2014-09-02 23:49:29

相關問題