I've written a code for removing the number from an array. When I run my code, it happens not to remove the number but instead gives me another number. For example, when I pass number 44 in order to remove it, the ouput happens to be 3 instead of removing it. What could be the problem?
Given input:
2 5 33 44 3 8 6 7 4
Sample output:
2 5 33 3 3 8 6 7 4
Code:
public class RemoveAtIndex {
public static void main(String[] args)
{
int[] myArray = {2, 5, 33, 44, 3, 8, 6, 7, 4};
int[] output = removeFromIndex(myArray, 44);
for(int i = 0; i < output.length; i++)
{
System.out.print(output[i] + " ");
}
}
public static int[] removeFromIndex(int[] myArray, int num)
{
int[] resultArray = new int[myArray.length - 1];
for(int i = 0; i < myArray.length; i++){
if(myArray[i] != num){
resultArray[i] = myArray[i];
}
else
resultArray[i] = myArray[i+1];
}
return resultArray;
}
}
sample inputandsample outputare generated by the program. Both have a length of9.