在Java中的`if`语句中声明一个变量,该变量根据条件的不同而不同

问题描述:

我知道,我知道,有很多简单的答案可以解决大多数情况。

I know, I know, there's a ton of simple answers that cover most cases for how to avoid this.

在我的情况下,我想使用用户-输入信息以在游戏中创建CPU玩家。如果用户选择简单模式,那么我想声明并实例化 EasyPlayer 类的实例。否则,我想声明并实例化 HardPlayer 类的实例。无论哪种方式,变量的特定名称都必须为 cpu,其余代码则不加区别地在 cpu上运行。也就是说,这些操作方式的所有差异都被构建到它们的不同类中,这些子类是 CpuPlayer 类的子类。

In my case, I want to use user-input info to create CPU players in a game. If the user chooses easy mode, then I want to declare and instantiate an instance of the EasyPlayer class. Otherwise, I want to declare and instantiate an instance of the HardPlayer class. Either way, the specific name of the variable needs to be "cpu" and the rest of the code operates on "cpu" indiscriminately. That is, all the differences in how these operate are built into their different classes, which subclass the CpuPlayer class.

所以这是代码:

// Set the opponent.
if (difficulty == 0){
    EasyPlayer cpu = new EasyPlayer(num_rounds);
}
else{
    HardPlayer cpu = new HardPlayer(num_rounds);
}

这给了我烦人的找不到符号错误。据我所知,每个人都说由于范围问题以及它永远不会发生的可能性,您不能在这样的条件下进行声明。

This gives me the ever-annoying cannot find symbol error. From what I can read, everyone says you cannot make declarations inside a conditional like this due to scope problems and the possibility that it never occurs.

如果是的话,根据用户输入,将单个变量声明为两个不同类之一的正确方法?

If so, what is the right way to alternatively declare a single variable as one of either of two different classes based on user input?

CpuPlayer cpu;

if (difficulty == 0){
    cpu = new EasyPlayer(num_rounds);
}
else{
    cpu = new HardPlayer(num_rounds);
}