java - 从任何位置删除数组元素并移动其余元素

问题描述 投票:1回答:2

我试图通过将值设置为0从数组中删除一个元素后移动数组的元素。如果我使用此代码块从数组的开头删除元素,我只能使用它。

if (balance[index] == 0 && acctNum[index] != 0) {
    numaccts--;
    acctNum[index] = 0;
    for(int count=0;count<numaccts;count++){
        acctNum[count]=acctNum[count+1];
        balance[count]=balance[count+1];
    }
acctNum[numaccts]=0;
balance[numaccts]=0;
}

这是我从数组中删除第一个值时获得的良好输出(在567834之前有一个值)。

567834    100.50
111111    0.0
222222    0.0
333333    0.0
444444    0.0

如果我删除除第一个以外的任何值,则数组未正确移位,这就是结果。 567834之前应该有一个数字,不应该有“0 0.00”。

567834    100.5
0    0.0
222222    0.0
333333    0.0
444444    0.0

我认为问题在于这篇文章中的第一个代码块,但是我无法修复它。我认为创建临时变量不会解决问题。有任何想法吗?

java arrays
2个回答
0
投票

你只想把东西从新创建的洞之外移开。您可能需要稍加注意,以下处理最后一个插槽而不读取超出阵列末尾的内容。但这应该是一个好的开始。

    if (balance[index] == 0 && acctNum[index] != 0) {
    numaccts--;
    acctNum[index] = 0;//handles case when index is at the end
    for(int count=index;count<numaccts;count++){//start from hole, shift over from beyond there
        acctNum[count]=acctNum[count+1];
        balance[count]=balance[count+1];
    }
acctNum[numaccts]=0;
balance[numaccts]=0;
}

0
投票

您的问题是您为for循环中的count变量赋值0,而不是给出您需要删除的元素的索引。

private void deleteAndShift(int [] balance, int [] acctNum, int index, int numaccts) {
    if(isValidAccount(balance, acctNum, index)) {
        numaccts--;
        acctNum[index] = 0;
        for(int count=index;count<numaccts;count++){
            acctNum[count]=acctNum[count+1];
            balance[count]=balance[count+1];
        }
    acctNum[numaccts]=0;
    balance[numaccts]=0;

    }
}

private boolean isValidAccount(int[] balance, int[] acctNum, int index) {
    return balance[index] == 0 && acctNum[index] != 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.