Hello I'm practicing to code in
java and here's one of the problem I'm trying to solve:
Given an array of positive ints, return a new array of length "count" containing the first even numbers from the original array. The original array will contain at least "count" even numbers.
copyEvens({3, 2, 4, 5, 8}, 2) → {2, 4}
copyEvens({3, 2, 4, 5, 8}, 3) → {2, 4, 8}
copyEvens({6, 1, 2, 4, 5, 8}, 3) → {6, 2, 4}
Here is my solution:
Now my problem is this:
1. If I run the code, it returns {0, 0, 0 ... (length)} // I think it has something to do with "pass by value" I think?
2. To solve this number 1 problem, I tried to return the output inside the loop. To do this, I replaced the 'break' by 'return output' and erase the 'return output' outside the loop. But it doesn't compile and here's the error message:
Error: public int[] copyEvens(int[] nums, int count) {
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This method must return a result of type int[]
Possible problem: the if-statement structure may theoretically
allow a run to reach the end of the method without calling return.
Consider using a final else {... to ensure that return is always called.
Can you help me improve my code and can you clarify me some rules regarding pass by value, return, and if else statement? I'm confused. Thanks!