我正在尝试在我正在编写的程序中创建两个玩家。问题是可以创建三种类型的玩家,但为了稍后引用它们,我希望将它们命名为玩家一和玩家二。三个类:“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;
}
}
最佳答案
感谢老程序员:
Change "Human player[i] = new Human();" to "player[i] = new Human();", etc.
了解派生类的工作原理非常重要,我很高兴这就是它的工作原理。非常感谢你,我希望这可以帮助将来的人。这是我更新的代码以进行全面说明:
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();
}
}
关于java - 使用派生类创建对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58260387/