我正在尝试在我正在编写的程序中创建两个玩家。问题是可以创建三种类型的玩家,但为了稍后引用它们,我希望将它们命名为玩家一和玩家二。三个类:“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;
}
}
白板的微信
相关分类