Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a variable inside an `if` statement in Java that is a different type depending on the conditional

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?

like image 228
ely Avatar asked Feb 09 '12 03:02

ely


People also ask

Can you declare variables in an if statement Java?

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 .

How do you use a variable inside an if statement?

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.

Is it possible to declare different types of variables on the same line in Java?

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.

How do you assign a condition to a variable in Java?

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.


1 Answers

CpuPlayer cpu;

if (difficulty == 0){
    cpu = new EasyPlayer(num_rounds);
}
else{
    cpu = new HardPlayer(num_rounds);
}
like image 187
James Montagne Avatar answered Nov 14 '22 22:11

James Montagne