Question: Write a code in Java that removes all odd elements from a partially filled array without using an array list or array import. Can you
Write a code in Java that removes all odd elements from a partially filled array without using an array list or array import.
Can you modify my code and provide an explaination on what I'm doing wrong? Thanks.
This is my attempt at it:
import java.util.Arrays;
public class RemoveTester { /** Removes all odd elements from a partially filled array @param values a partially filled array @param size the number of elements in values @return the new size */ public static int removeOdd(int[] values, int size) { int pos = 0; int i = pos + 1; while ( i < size) { if ( values[i] % 2 == 1) { values[i] = values[size -1]; size--; } else i++; } return size; }
public static void main(String[] args) { int[] a = { 22, 98, 95, 46, 31, 53, 82, 24, 11, 19 }; int sizeBefore = 8; int sizeAfter = removeOdd(a, sizeBefore); System.out.print("a: [ "); for (int i = 0; i < sizeAfter; i++) { System.out.print(a[i] + " "); } System.out.println("]"); System.out.println("Expected: [ 22 98 46 82 24 ]");
int[] b = { 23, 97, 95, 45, 31, 53, 81, 24, 11, 19 }; sizeBefore = 7; sizeAfter = removeOdd(b, sizeBefore); System.out.print("b: [ "); for (int i = 0; i < sizeAfter; i++) { System.out.print(b[i] + " "); } System.out.println("]"); System.out.println("Expected: [ ]"); }
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
