Reputation: 9
I have a method that should return an object type at the end. im using if statements and returning object type accordingly, but i keep getting an error saying i didnt return anything? now sure how to solve it.
private Door pickADoor(Door door1, Door door2, Door door3) {
Random generator = new Random();
int numOfDoors = generator.nextInt(3) + 1;
if (numOfDoors == 1) {
door1.choose();
System.out.println("The player selected door A");
return door1;
} else if (numOfDoors == 2) {
door2.choose();
System.out.println("The player selected door B");
return door2;
} else if (numOfDoors == 3) {
door3.choose();
System.out.println("The player selected door C");
return door3;
}
}
Upvotes: 0
Views: 122
Reputation: 2153
You are missing a return statement in after the if block,
private Door pickADoor(Door door1, Door door2, Door door3) {
Random generator = new Random();
int numOfDoors = generator.nextInt(3) + 1;
if (numOfDoors == 1) {
door1.choose();
System.out.println("The player selected door A");
return door1;
}
else if (numOfDoors == 2) {
door2.choose();
System.out.println("The player selected door B");
return door2;
}
else if (numOfDoors == 3) {
door3.choose();
System.out.println("The player selected door C");
return door3;
}
// decide what should you do here
throw new IllegalStateException("only 3 doors selectable");
}
Upvotes: 0
Reputation: 18825
You miss the else block. Although logically there shouldn't be any, the compiler cannot know that. So add something like:
else {
throw new IllegalStateException ("cannot happen");
}
Edit: or simply assert false
, as suggested below. This doesn't give explanation but here clearly is not necessary.
Upvotes: 3
Reputation: 297
you need return
statement for all other scenarios. Example if numOfDoors
would be greater than 3 or less than 1. In this case nothing would be returned. It is inadmissible. Just add to your code
else return null;
...or default door... depend of your logic
Upvotes: 0
Reputation: 26
The issue is that java thinks there could be a scenario in which numOfDoors
could be a number other than 1, 2, or 3. Logically, however, we know that your random number will be from 1-3 inclusive, it's just java doesn't realize this.
Instead, you can change your last else if
to this:
else {
door3.choose();
System.out.println("The player selected door C");
return door3;
}
}
Upvotes: 1
Reputation: 9559
It is complaining because you don't cover all of the possibilities in your if
statements, you only cover the cases where numOfDoors
is 1,2, or 3. Maybe nofOfDoors
can only be 1,2 or 3 but the compiler doesn't know that.
One possible fix: on your final else
change
else if(numOfDoors == 3) {
to be
else {
So it covers all other values.
Upvotes: 1