使用派生类创建对象数组

问题描述 投票:0回答:1

我正在尝试在正在编写的程序中创建两个播放器。问题是可以创建三种类型的播放器,但是为了以后引用它们,我希望将它们命名为播放器一和播放器二。三个类别:“人”,“计算机”和“卡伦”是“玩家”的派生类别。我想知道如何创建一个数组播放器,然后可以将播放器1和播放器2对象放入其中。这可能吗?

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

}

[我尝试了另一种方法,根据我们在(i)上进行的for循环迭代,使用if语句使对象成为playerOne或playerTwo。不幸的是,尽管只有一个声明可以运行,但它看起来并不像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;
}

}

java arrays object derived-class derived
1个回答
0
投票

感谢OldProgrammer:

更改“人类玩家[i] = new Human();”改为“ player [i] = new Human();”,等等。

了解派生类的真正重要性,我很高兴这是它的工作方式。非常感谢您,希望以后对您有所帮助。这是我的更新代码,以进行全面说明:

int highestScore = 0;
Player[] player = new Player[2]; 

Scanner userInput = new Scanner (System.in);

for (int i = 0; i < 2; 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());

  switch (playerType)
    {
      case 1:
        player[i] = new Human();
      case 2:
        player[i] = new Computer();
      case 3:
        player[i] = new Karen();
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.