Arrays: question about "removing" items.
hello.. guys
i am trying to figure out how to remove "some" x from array..
i had this so far..
but still i get errors :S with..
Code :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Even.remove(Even.java:150)
at Even.main(Even.java:127)
Code :
public static int[] remove(int[] arr,int x) {
int count=0;
for (int i=0;i<arr.length;i++)
if (arr[i] == x)
count++;
int[] array = new int[arr.length-count];
for (int i=0;i<arr.length;i++)
if (arr[i] != x)
array[i]=arr[i];
return array;
}
Re: Arrays: question about "removing" items.
You're copying over values into the same indices between the two arrays, leaving blank spots in array.
Code :
count = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i]!=x)
{
array[count] = arr[i];
count++;
}
}
Re: Arrays: question about "removing" items.
good.. i forgot that :P
thanks alot
Code :
public static int[] remove(int[] arr,int x) {
int count=0,k=0;
for (int i=0;i<arr.length;i++)
if (arr[i] == x)
count++;
int[] array = new int[arr.length-count];
for (int i=0;i<arr.length;i++)
if (arr[i] != x)
{
array[k]=arr[i];
k++;
}
return array;
}