I have to create a method that takes in an array and value as arguments and returns a new array with the specified value removed.
Here's my attempt:
public static int[] remove(int[] nums,int value){
int[] after = new int[nums.length-1];
for (int i = 0; i < nums.length; i++) {
if (!(nums[i] == value)) {
after[i] = nums[i];
}
}
nums = after;
return nums;
}
The code throws
ArrayIndexOutOfBoundsException
bur I don't know why.
Code is trying to copy values from original array to new array leaving a blank or space(value 0) in place of targeted value. The error
ArrayIndexOutOfBoundsExceptionis showing because you are initialising the after with nums.lenth-1int[] after = new int[nums.length-1];You can change that or swap the targeted element with the last element and copy entire array except the last.And I am assuming that there is only one target element