I am creating a method that returns the variable elt if it exists in an array. If it does not exist in an array, I need to return null.
The issue is, I am checking for the variable elt in each item in the array using an if statement in a for-loop. I do not think I can put a return statement at the end of the if statement in the for-loop, because each time it executes the if statement, the potential return value would be different. I think this would make a new return value each time the for-loop was looped through. To solve this, I created a boolean temp variable called exist. If true, the method will return the variable elt. If false, it will return null. The code I am working with is below.
public T remove(T elt) {
boolean exist;
for (int i=0; i<data.length; i++) {
if (data[i] == elt) {
data[i] = null;
size--;
exist = true;
System.out.println(exist);
for (++i; i < data.length; i++) {
data[i-1] = data[i];
}
}
}
if (exist = true)
return elt;
else
return null;
}
My question is, is there a way to tuck the return statement in the method without using a temp variable?
returnin aforloop. The method will finish and exit as soon as you return.eltindata, while the accepted solution only removes first encountered occurrence (and exits immediately). This might be good or bad depending on your method's contract.ivarible, moving that one to the end of array in the process. Not a good practice by the way, I recommend you don't touch the iteration variable unless necessary. Second thing, you shift all remaining items left, so so you'll skip testing / removing the former (i+1)-th element - that could be fixed by replacing theifwithwhile.if (exist = true)will always evaluate totrue, sinceexist = trueis an assignment - you'll want==there instead of=if you're trying to make that code work.