Question: Question: Write and test a CopyEvens.java program with a copyEvens() method that returns a new array containing just the even numbers in its input int
Question: Write and test a CopyEvens.java program with a copyEvens() method that returns a new array containing just the even numbers in its input int array (if any):
copyEvens will have the following header:
public static int[] copyEvens(int[] a)
copyEvens should go through the array a passed into the method to determine how many even integers are in a, then create a new array of that size and copy the even ints in a into the new array and return it.
Hint: use a separate counter variable to fill up the new array as youre going through the a array in a for loop.
In addition, write a helper method countEvens() with this header:
private static int countEvens(int[] a) // counts the number of even ints in a and returns that count.
copyEvens should call the countEvens() method to determine the size of its returned array.
Note: your copyEvens method must work if there are no even elements in a, and return a 0-length array in that case.
Template below:
public class CopyEvens { private static final Scanner170 input = new Scanner170(System.in); // for readArray public static int[] readArray() // a method to read in an int array from the keyboard { System.out.print("Enter the number of whole numbers to put into an array: "); int numElements = input.nextInt(); if (numElements <= 0) return new int[0]; int[] output = new int[numElements]; System.out.println("Enter the whole numbers, one per line, or on a single line separated by spaces:"); for (int i = 0; i < numElements; i++) output[i] = input.nextInt(); return output; } private static void display(String header, int[] a) // a method to display an array, possibly with a header String { if (header.length() != 0) System.out.print(header + " "); if (a.length > 0) { for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } else System.out.println("no elements"); System.out.println(); } // Return an array containing just the even ints in the input array public static int[] copyEvens(int[] a) // copy just the even elements of a to the returned array { /* your code for the copyEvens method goes below this comment */ } private static int countEvens(int[] a) // count the number of even elements in a and return that count { /* your code for the countEvens method goes below this comment */ } public static void main(String[] args) { int[] example = readArray(); // get an array from the user display("Original array:", example); example = copyEvens(example); // change the array that example refers to System.out.println("Number of even values: " + countEvens(example)); display("Array of evens:", example); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
