I’m creating a simple football video game with object oriented programming. One problem I’m having is a method with a return type of a custom object is not returning with said object. More specifically:
I wrote the Player class (which corresponds with a football player, not the user) which has an attribute called carrier. This attribute is a boolean which is set to false by default. In the main class, I’m writing a method of return type Player which iterates through an array of Player objects, called offense, to find the one where carrier is set to true. It looks like this:
Player getCarrier() {
for(int i = 0; i < offense.length; i ++) {
if(offense[i].carrier) {
return offense[i];
}
}
}
However, the compiler is saying that the method is not returning an object of type Player. What is wrong here?
The problem here is when all the players in the array are not carriers i.e. offense[i].carrier is false for all elements in the array. It means the loop will finish without visiting the return statement.
The method is required to return an object of type Player or subclass of type Player for all paths through the method.
So the method should be
Player getCarrier() {
for(int i = 0; i < offense.length; i ++) {
if(offense[i].carrier) {
return offense[i];
}
}
return null;
}
and you would have to test the return value and see if it is null before using it otherwise you will get a NPE (Null Pointer Exception) error
On the other hand: when you iterate here you search an information (find the one where carrier is set to true) that you have stored yourself right before.
So instead of searching the information you could go to the place (ALL places where you set carrier to true and additionally store the Player index: carrierPlayerIndex
Then the function would just be:
Player getCarrier() {
if(carrierPlayerIndex!=null&&carrierPlayerIndex>-1)
return offense[carrierPlayerIndex];
else
return null;
}