簡體   English   中英

拋出異常

[英]Throw an Exception

對於我的作業,我們被要求添加手動 IndexOutOfBoundsException。

public int get(Object[] objArr){
    size = objArr.length;
    for(int i = 0; i < size; i++ )
        if(objArr[i] < 0 || objArr[i] > objArr.length )
        {
            throw new IndexOutOfBoundsException("I must be greater than 0 and less than " + size);
        }

我試圖讓代碼循環查看並檢查小於 0 的數字,並且它們的索引在用戶聲明的數組之外。 我的 if 語句出現錯誤,想知道如何解決這個問題。

當您獲得一個小於數組大小的輸入索引 i 時,您必須拋出異常。

喜歡:

public void get(Object[] objArr, Integer i){
    size = objArr.length;
    if(i<0 || i >= size){
       throw new IndexOutOfBoundsException("I must be greater than 0 and less than " + size);
    } 
}

首先你應該在進入 for 循環之前拋出期望,然后你需要檢查索引,而不是索引處對象的值:

if(i < 0 || i >= objArr.length )

暫無
暫無

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

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