我有一个方法,应该在最后返回一个对象类型。即时通讯使用if语句并相应地返回对象类型,但是我一直收到错误消息,说我什么也没返回?现在确定如何解决它。

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;
        }
    }

最佳答案

您错过了else块。尽管从逻辑上讲不应有任何内容,但编译器无法知道这一点。因此,添加类似以下内容:

 else {
      throw new IllegalStateException ("cannot happen");
 }


编辑:或简单地assert false,如下所示。这没有给出解释,但是这里显然没有必要。

09-13 05:37