I know, I know, there's a ton of simple answers that cover most cases for how to avoid this.
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.
So here's the code:
// 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?
Java allows you to declare variables within the body of a while or if statement, but it's important to remember the following: A variable is available only from its declaration down to the end of the braces in which it is declared. This region of the program text where the variable is valid is called its scope .
If you're new to the syntax that's used in the code sample, if (int i = 5) { is a perfectly valid way of declaring and defining a variable, then using it inside the given if statement. It allows us to write terser, clearer code, while also avoiding limiting the scope of a variable.
Declaring each variable on a separate line is the preferred method. However, multiple variables on one line are acceptable when they are trivial temporary variables such as array indices.
The line: if(b = ! b) first reverses (or technically "negates") the value of b and then "assigns" it to b. It is good to know that assignment operation in Java returns the object to which value is being assigned. So, the value of b is returned as the condition for if-statement.
CpuPlayer cpu;
if (difficulty == 0){
cpu = new EasyPlayer(num_rounds);
}
else{
cpu = new HardPlayer(num_rounds);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With