Reputation: 1726
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?
Upvotes: 1
Views: 2155
Reputation: 3785
There is no need to use one extra variable . You can directly return from for loop. Instead of writing exist = true
write return elt
and at the end
instead of
if (exist = true)
return elt;
else
return null;
just write return null
so that if elt
doesnt exist it will return null.
Upvotes: 3
Reputation: 3998
You can put a return statement almost anywhere.
To answer your question, you could put a return after your inner for loop like follows:
public T remove(T elt) {
for (int i=0; i<data.length; i++) {
if (data[i] == elt) {
data[i] = null;
size--;
System.out.println(exist);
for (++i; i < data.length; i++) {
data[i-1] = data[i];
}
return elt;
}
}
return null;
}
Upvotes: 3