-1
我正在嘗試用Java編寫一個Player
類,該類有兩個子類:HumanPlayer
和ComputerPlayer
。我想允許用戶選擇與哪個玩家對戰,並且一旦選擇 - 創建相關對象並進行遊戲。處理對象的範圍
由於對象是在if語句中創建的,因此編譯器不允許我在if範圍之外執行任何操作。在其它情況下,我將創建類範圍內的對象,但在這種情況下我不能提前知道哪些對象來創建(人/計算機)
這裏是爲了說明某些代碼:
public class Player {
private String name;
public String getName(){
return name;
}
}
public class HumanPlayer extends Player {
public void play(){
System.out.println("Human playing");
}
}
public class ComputerPlayer extends Player {
public void play(){
System.out.println("Computer playing");
}
}
import java.util.Scanner;
public class PlayerDriver {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please type 1 for human, 2 for computer");
int selection = in.nextInt();
if (selection==1){
HumanPlayer player = new HumanPlayer();
} else if (selection==2){
ComputerPlayer player = new ComputerPlayer();
} else {
throw new IllegalArgumentException("invalid answer");
}
Player.play(); //can't do that
}
}
完美!感謝您的快速回復 – user2314782