In Java, when I'm building up a new array based on an array that's taken in as a parameter. For example, say I want to build an array with all values of the given array except for the sevens, so I want to take {5,7,8,9,7,3} and return {5,8,9,3} without modifying the input array. In python, this would be very simple, and I would do something like this:
def no7s(x):
y=[]
for num in x:
if num!=7:
y+=[num]
return y
In java this seems much more complicated. Here's what I've tried:
public static int[] no7s(int[] x){
int size=0;
for (int num: x){
if (num!=7){
size+=1;
}
}
int[] y = new int[size];
for (int i=0; i<x.length; i++){
if (x[i]!=7){
y[i]=x[i];
}
}
return y;
}
I'm getting confused about the last for loop; what I have now does not work, but I'm not sure what I should be doing instead. I'm pretty sure the issue is that x.length>size, but I don't know how to account for this.