ロバート:
ランタイム上のAN配列から要素を削除する方法はありますか?
例えば:
int[] num = {8, 1, 4, 0, 5};
Output:
Enter the Index: 0
1, 4, 0, 5
Enter the Index: 3
1, 4, 0
Enter the Index: 1
4, 0;
私はそれを使用して、初期化され、サンプルこの種の問題にされると、あなたは配列の長さのサイズを変更することができないことを知ってArrayList
はるかに実用的です。しかし、単にアレイを使用することにより、この種の問題を行う方法はありますか?
私は1つの要素を削除し、配列-1新しい配列を作成し、その中に、元の配列の値をコピーして表示するために管理してきました。しかし、問題は、出力の次の反復では私はまだ要素を削除することができているが、サイズは変更されません。
これは何が起こるかです:
int[] num = {8, 1, 4, 0, 5};
Output:
Enter the Index: 0
1, 4, 0, 5 // in the first loop it goes as I want it.
Enter the Index: 2
1, 4, 5, 5 // this time array's length is still 4 and just duplicates the last value
Enter the Index: 1
1, 5, 5, 5 // length is still the same and so on.
これは、配列から要素を削除するに私のコードです:
public static int[] removeElement(int index, int[] n) {
int end = n.length;
for(int j = index; j < end - 1; j++) {
n[j] = n[j + 1];
}
end--;
int[] newArr = new int[end];
for(int k = 0; k < newArr.length; k++) {
newArr[k] = n[k];
}
displayArray(newArr);
return newArr;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = {8, 1, 4, 0, 5};
for(int i = 0; i < num.length; i++) {
System.out.print("Enter the Index: ");
int index = input.nextInt();
removeElement(index, num);
}
}
public static void displayArray(int[] n) {
int i = 0;
for(; i < n.length - 1; i++) {
System.out.print(n[i] + ", ");
}
System.out.print(n[i]);
}
配列にこれを行う方法のトリックはありますか?それとも私は実際に使用しなければなりませんのArrayList
?
彼らは次のとおりでした:
あなたは、によって返された新しい配列を破棄していますremoveElement
。
あなたのループを次のように変更します
for(int i = 0; i < num.length; i++) {
System.out.print("Enter the Index: ");
int index = input.nextInt();
num = removeElement(index, num);
}