double値をdouble配列に入れるための、一見問題のない方法があります。それは
insert(int i, double value)
ここで、i はインデックス (array[i]) で、value はそのインデックスに必要なものです。
メソッドをエッジケースに分割し、初期化された配列スペース (長さ) の十分な安全なブロックを組み込み、要素数が長さ以上になるたびに長さを 2 倍にするメソッドの一部でそれをバッファリングしました。次に、入力 i が配列の項目数 (numItems) より大きい場合と numItems より小さい場合のメソッドを配置します。i < numItems は正常に動作していますが、入れようとすると
insert(63,3)
insert(15,3)
insert(23,3)
配列に入れると、(1,-1,5,23)
配列の最後の部分で 3 が 2 つしか得られません。私の最初の配列の長さは 10 なので、メモリの問題ではありません。print メソッドのエラーかもしれないと思い、最後の要素を手動で取得しようとしたところ、インデックスが空であることがわかりました。したがって、これは次の私の方法の論理エラーです。
// 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;
}
}