我有一种方法,看起来很好,可以将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;
}
}
请在三次调用之后提供数组的定义部分。 (项[0]〜项[6],如果我明白你的方法正确。) –
1.0 -1.0, 5.0, 23.0, 3.0, 3.0 及以后,我得到一个0.0,为此,该阵列是已初始化 – Sukwoo
您是否使用不同的double值对其进行了测试?这个测试的结果是什么? numItems的值在其他地方改变了吗? –