2012-09-28 223 views
0

我有一種方法,看起來很好,可以將double值放入雙數組中。它是將元素插入到雙數組中

insert(int i, double value) 

其中i是索引(數組[i])和值是我想要在該指數。

我將該方法拆分爲邊緣情況,內置在充分安全的初始化數組空間(長度)的安全塊中,並且每當元素的數量等於或大於長度。然後,當輸入i大於數組的項數(numItems)並且小於numItems時,我會放入方法。我< numItems的工作正常,但是當我試圖把在

insert(63,3) 
insert(15,3) 
insert(23,3) 

到我(1,-1,5,23)陣列我只得到2個三條對我的數組的最後一部分。我的初始數組長度是10,所以它不是內存問題。我認爲這可能是一個打印方法錯誤,並試圖手動獲取最後一個元素,這告訴我索引是空的。因此,在我的方法中,這是一個邏輯錯誤,接下來是。

// if i is greater than the number of items, insert value into numItems index, 
// and not any farther. e.g. if i = 100000 and numItems = 10, put value into 
// items[10] and not items[100000]; 
if (i > numItems) 
{ 
    items[numItems] = value; 
    numItems++; //add to counter 
    return; 
} 

事情是,它是這樣簡單的代碼,我不能告訴它有什麼問題。非常直觀,而且非常令人費解。想法?下面

是插入方法

public void insert(int i, double value) //insert value into array[i] 
{ 
    if(i < 0) 
    { 
     System.out.println("i < 0; please input i >= 0 for array indices."); //an array cannot have an indice < 0; 
     return; 
    } 

    if (numItems >= items.length) // if the number of items becomes equal or greater than the array containing it 
    { 
     double[] tempItems = new double [items.length * 2]; // create a new array double the size of current 
     for(int j =0 ; j < items.length; j++) //and copy all elements into the new array 
     { 
      tempItems[j] = items[j]; 
     } 

     items = tempItems; //set the temp array as the main array. 
    } 

    if (i > numItems) //if i is greater than the number of items, insert value into numItems index, and not any farther. 
    {     // i.e. if i = 100000 and numItems = 10, put value into items[10] and not items[100000]; 
     items[numItems] = value; 
     numItems++; //add to counter 
     return; 
    } 

    if (i < numItems) //if i is inside the used boundaries of the array 
    { 
     for (int k = numItems; k > i; k--) //shift values over to the right. 
     { 
      items[k]=items[k-1]; 
     } 

     items[i] = value; //and insert value into i 
     numItems++; //add to counter 
     return; 
    } 


} 
+1

請在三次調用之後提供數組的定義部分。 (項[0]〜項[6],如果我明白你的方法正確。) –

+0

1.0 -1.0, 5.0, 23.0, 3.0, 3.0 及以後,我得到一個0.0,爲此,該陣列是已初始化 – Sukwoo

+0

您是否使用不同的double值對其進行了測試?這個測試的結果是什麼? numItems的值在其他地方改變了嗎? –

回答

0

的整個在這種改變的陣列大小(插入或刪除)時,建議使用java.util.List實現任何修改的情況下例如,ArrayList。通過臨時陣列和移動元素,它可以幫助您避免頭痛。

此外,要複製陣列中的某些元素,您應該考慮使用System.arraycopy等現有方法以及java.util.Arrays的各種複製方法。

+0

唯一的是我試圖不使用這些...嘗試和實施的東西 – Sukwoo