Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

2.16 Lab 1: Remove all even numbers from an array Write the removeEvens() method, which receives an array of integers as a parameter and returns

2.16 Lab 1: Remove all even numbers from an array

Write the removeEvens() method, which receives an array of integers as a parameter and returns a new array of integers containing only the odd numbers from the original array. The main program outputs values of the returned array.

Hint: If the original array has even numbers, then the new array will be smaller in length than the original array and should have no blank elements.

Ex: If the array passed to the removeEvens() method is [1, 2, 3, 4, 5, 6, 7, 8, 9], then the method returns and the program output is:

[1, 3, 5, 7, 9] 

Ex: If the array passed to the removeEvens() method is [1, 9, 3], then the method returns and the program output is:

[1, 9, 3] 

Code I have so far but not sure if it is all 100% right:

import java.util.Arrays; public class LabProgram { public static int[] removeEvens(int [] nums) { /* Type your code here */ // figure out how big array needs to be int oddCounter = 0; for(int i = 0; i < nums.length; i++) { //find out if number is odd // keep track of how many odd number if (nums[i] % 2 != 0) { //number is odd oddCounter ++; nums[i] = oddCounter; return nums; } else { //number is even } } int[] odds = new int[oddCounter]; return odds; } public static void main(String[] args) { int [] input = {1,2,3,4,5,6,7,8,9}; int [] result = removeEvens(input); // Helper method Arrays.toString() converts int[] to a String System.out.println(Arrays.toString(result)); // Should print [1, 3, 5, 7, 9] } } 

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Repairing And Querying Databases Under Aggregate Constraints

Authors: Sergio Flesca ,Filippo Furfaro ,Francesco Parisi

2011th Edition

146141640X, 978-1461416401

More Books

Students also viewed these Databases questions

Question

What is the difference between continuous and discrete data?

Answered: 1 week ago

Question

12-5 How will MIS help my career?

Answered: 1 week ago

Question

=+2. How did the study operationally define these variables?

Answered: 1 week ago