And if you don’t even get on for
? This mechanism will only be executed if there is an element in the collection, if the data collection is empty or enters the loop, then it goes to the end of the method and what is it returning? Nothing! There’s one missing return
in this case and that makes sense, then "it seems" that false
is suitable but not sure without knowing the requirements.
The for
is still a conditional execution (branch), then it needs to be considered. You have to consider all possible paths when giving a return
in the method. Something like this could solve:
public class Biblioteca {
private ArrayList<Exemplar> exemplares;
public boolean emprestar(int codigo) {
for (Exemplar e : exemplares) {
if (e.getCodigo() == codigo) return e.isDisponivel();
else return false;
}
return false;
}
}
I think all the code has other problems, but I can only solve this one. An example is that this will only evaluate the first item of the data collection, no matter what happens it will terminate the method after the first item, so I think you put the return
randomly misplaced, cannot place a return
anywhere, you might want to do this:
public class Biblioteca {
private ArrayList<Exemplar> exemplares;
public boolean emprestar(int codigo) {
for (Exemplar e : exemplares) if (e.getCodigo() == codigo) return e.isDisponivel();
return false;
}
}
I put in the Github for future reference.
This way if you find a code that matches what you are looking for it returns if it is available or not according to the method isDisponivel()
, but if you can’t find the code, that is, go through everything and no code is the same, then surely you should return a false one because if you don’t even have the code, it is certainly unavailable.
The method name seems wrong, it is doing a check is not lending anything.
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).
– Maniero