谁应该先走?静态变量问题

Who should go first? Static variable issue

我正在为一项大学作业创建一个游戏,其中一个标准是程序询问谁先走。

我在这方面遇到了一些麻烦,因为我最初将 ComputerPlayer firstPlayerComputerPlayer secondPlayer 定义为 null,然后根据按钮按下来设置值,但是我由于先前已经定义了玩家,因此不断出现错误。

任何人都可以帮助我重新措辞以使其有效吗?谢谢

   public static void main(String[] args){
        JPanel panel = new JPanel();
        JRadioButton button1 = new JRadioButton("Human");
        JRadioButton button2 = new JRadioButton("Computer");
        panel.add(new JLabel("Who Goes First?"));
        panel.add(button1);
        panel.add(button2);
        ComputerPlayer firstPlayer = null;
        ComputerPlayer secondPlayer = null;

        JOptionPane.showMessageDialog(null, panel);


        if(button1.isSelected()) {       
            ComputerPlayer firstPlayer = new HumanPlayer();
            ComputerPlayer secondPlayer = new AIPlayer();
        }

        if(button2.isSelected()) {       
            ComputerPlayer firstPlayer = new AIPlayer();
            ComputerPlayer secondPlayer = new HumanPlayer();
        }

        GameLogic logic = new GameLogic();

        logic.addPlayer(firstPlayer); 
        logic.addPlayer(secondPlayer); 

        logic.startGame();
    }
    if(button1.isSelected()) {       
        ComputerPlayer firstPlayer = new HumanPlayer();
        ComputerPlayer secondPlayer = new AIPlayer();
    }

    if(button2.isSelected()) {       
        ComputerPlayer firstPlayer = new AIPlayer();
        ComputerPlayer secondPlayer = new HumanPlayer();
    }

您正在为这些未使用的局部变量赋值。不管你想做什么这些方法都是错误的。

删除 if 块中的 "ComputerPlayer"。您已经创建了此对象,因此您无需再次创建。

if(button1.isSelected()) {       
    firstPlayer = new HumanPlayer();
    secondPlayer = new AIPlayer();
}

if(button2.isSelected()) {       
    firstPlayer = new AIPlayer();
    secondPlayer = new HumanPlayer();
}