使用派生类创建对象数组

我正在尝试在我正在编写的程序中创建两个玩家。问题是可以创建三种类型的玩家,但为了稍后引用它们,我希望将它们命名为玩家一和玩家二。三个类:“Human”、“Computer”和“Karen”是“Player”的派生类。我想知道如何创建一个数组 Player,然后我可以将player1 和player2 对象放入其中。这可以吗?


int playerType = 0;

int highestScore = 0;

Player[] player = new Player[2]; // This is the array of type Player, the master class


Scanner userInput = new Scanner (System.in);


for (int i = 1; i < 3; i++)

{

    System.out.println ("Choose a type of player:");

    System.out.println ("1: Human");

    System.out.println ("2: Computer (Threshold = 20)");

    System.out.println ("3. Computer (Custom)");

    System.out.print ("? : ");


    playerType = Integer.valueOf(userInput.nextLine()); // gets input choice from user



  switch (playerType)

    {

      case 1:

        Human player[i] = new Human();

      case 2:

        Computer player[i] = new Computer();

      case 3:

        Karen player[i] = new Karen();

    }


}

我尝试了另一种方法,使用 if 语句根据我们所在的 for 循环的迭代来创建对象playerOne 或playerTwo (i)。不幸的是,java 似乎不会编译它,因为同一个变量有多个声明,即使只有其中一个声明应该运行。


if(playerNumber == 1){

  switch (playerType)

    {

      case 1:

        Human playerOne = new Human();

      case 2:

        Computer playerOne = new Computer();

      case 3:

        Karen playerOne = new Karen();

    }

}


if(playerNumber == 2){

  switch (playerType)

    {

      case 1:

        Human playerTwo = new Human();

      case 2:

        Computer playerTwo = new Computer();

      case 3:

        Karen playerTwo = new Karen();

    }

}

OldProgrammer 建议的解决方案如下,效果非常好。但是,我现在在调用以下方法时遇到问题:人类、计算机和凯伦。尝试执行时出现以下错误:


System.out.println(player[i].getName() + ", your turn");

错误消息:


Main.java:38: error: cannot find symbol

    System.out.println(player[i].getName() + ", your turn");

                                ^

symbol:   method getName()

location: class Player

1 error

每个类中的方法如下所示:


public class Karen extends Player {

private String playerName = "Karen";


public String getName(){

  return playerName;

}

}


潇潇雨雨
浏览 71回答 1
1回答

白板的微信

感谢老程序员:更改“人类玩家[i] = new Human();”&nbsp;到“player[i] = new Human();”等了解派生类的工作原理非常重要,我很高兴这就是它的工作原理。非常感谢你,我希望这可以帮助将来的人。这是我更新的代码以进行全面说明:int highestScore = 0;Player[] player = new Player[2];&nbsp;Scanner userInput = new Scanner (System.in);for (int i = 0; i < 2; i++){&nbsp; &nbsp; System.out.println ("Choose a type of player:");&nbsp; &nbsp; System.out.println ("1: Human");&nbsp; &nbsp; System.out.println ("2: Computer (Threshold = 20)");&nbsp; &nbsp; System.out.println ("3. Computer (Custom)");&nbsp; &nbsp; System.out.print ("? : ");&nbsp; &nbsp; playerType = Integer.valueOf(userInput.nextLine());&nbsp; switch (playerType)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; case 1:&nbsp; &nbsp; &nbsp; &nbsp; player[i] = new Human();&nbsp; &nbsp; &nbsp; case 2:&nbsp; &nbsp; &nbsp; &nbsp; player[i] = new Computer();&nbsp; &nbsp; &nbsp; case 3:&nbsp; &nbsp; &nbsp; &nbsp; player[i] = new Karen();&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java