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

assign value to variable in if statement java
how to use a variable outside of an if statement java
java variable might not have been initialized if statement
declare variable in if statement javascript
declare variable in if statement c
can you declare a variable in an if statement
assign a variable in an if statement
declare variable in if statement c#

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?

CpuPlayer cpu;

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

Initialization of local variable in a conditional block in Java , In all these blocks, if the specified condition is true, the code inside the block is The above-given points are true for both primitive and reference type local part of the condition, and another variable is initialized inside the conditional block,  Java is a strongly typed programming language. This means that every variable must have a data type associated with it. For example, a variable could be declared to use one of the eight primitive data types: byte, short, int, long, float, double, char or boolean.

If your intention is to call only methods available to the CpuPlayer class, then perhaps a better design pattern to use is the Strategy Pattern. In your case, you would probably add a new class called CpuStrategy, and modify your CpuPlayer constructor to something like:

public CpuPlayer(CpuStrategy strategy, int num_rounds)

This makes the rest of your code easier to read and probably easier to maintain too. Here's what your original snippet of code would look like:

CpuPlayer cpu = new CpuPlayer(new CpuStrategy(difficulty), num_rounds);

We got rid of the if/else since the CpuStrategy class will handle the difference between difficulty levels. This also makes sense since you can abstract away the notion of "difficulty levels" from the meat of your program, which I assume is the game playing part.

Programming via Java: Conditional execution, The most natural way of accomplishing this in Java is to use the if statement to do one thing if the condition is true and another thing if the condition is false. What's going on here is that the declaration of max inside the if 's body with a type, it counts as a declaration; and you can only declare each variable name once. Java Nested if..else Statement. In Java, it is also possible to if..else statements inside a if..else statement. It's called nested ifelse statement. Here's a program to find largest of 3 numbers: Example 4: Nested ifelse Statement

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

What If? Declaring variables in if statements, and the curiosities of , tl;dr: Variables declared in if statement conditions are accessible in the else statement as well. Please take a moment to peruse the following example code​, based and defining a variable, then using it inside the given if statement. Scope in C++ isn't just for functions — any time you open a new pair of  To create an array in Java, you use three steps: Declare a variable to hold the array. Create a new array object and assign it to the array variable. Store things in that array. Declaring Array Variables. The first step in creating an array is creating a variable that will hold the array, just as you would any other variable.

Declare it first, and then assign it.

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

Learning Java Through Games, As you can see, the new version is more compact and does not use an if-else values is assigned to the same variable based on the validity of a condition. store a finite number of different real numbers inside a variable of type double String s ⇒ Declares the variable s of type Data Types and Conditional Statements 35. Stack Overflow Public questions and answers; Declaring a variable inside an `if` statement in Java that is a different type depending on the conditional.

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

[PDF] Conditional statements, Java, like all other programming languages, is equipped with specific condition is an expression of type boolean, i.e., a conditional expression that is evaluated to true or When this if-else statement is executed, the string "bigger value = " followed by the bigger The variables declared inside the block are not visible. Java Variables. Variables are containers for storing data values. In Java, there are different types of variables, for example: String - stores text, such as "Hello". String values are surrounded by double quotes; int - stores integers (whole numbers), without decimals, such as 123 or -123

JAVA AND OBJECT-ORIENTED PROGRAMMING PARADIGM, Declaring variables inside block enables us to have more precise control over Label allows transferring program flow of control to other statements within the same function. If a data object is defined within a block all nested blocks can use that data In a conditional statement, depending on the result of evaluation of a  When you declare more than one variable in a single statement, each variable can have its own initializer: int x = 5, y = 10; When you declare two class or instance variables in a single statement but use only one initializer, the initializer applies only to the last variable in the list. For example: static int x, y = 5; Here, only y is

Hands-On Penetration Testing with Python: Enhance your ethical , The import statement is used to import the libraries in Python, just as we use For now, we will look at what the different Python keywords mean: false: The used to declare and use global variables. if: The conditional if statement. import: This functions. nonlocal: This is used to declare a variable inside a nested function  One use of the Java ternary operator is to assign the minimum (or maximum) value of two variables to a third variable, essentially replacing a Math.min(a,b) or Math.max(a,b) method call. Here’s an example that assigns the minimum of two variables, a and b , to a third variable named minVal :

Java if statements, This tutorial explains how Java's if statements work. Conditional Operators; Comparing Variables and Constants; Methods example tests the boolean variable isValid and based on its value (either true When the brackets are there​, it is easier to remember to insert new statements inside the brackets. The ____ statement is used to repeat a statement or series of statements as long as a given conditional expression evaluates to a truthy value. literal A single statement that declares a variable and specifies array values as its content is called an array ____.

Comments
  • +1 for realizing that the solution you have here is insufficient and coming to SO for help.
  • Ah. Major head-slapping moment. Thank you.
  • Thanks for the tip and the extra details. This is indeed a good re-design idea.
  • The null assignment at the beginning seems unnecessary, as there is an ELSE to the IF conditional. As long as HardPlayer inherits from CpuPlayer, and HardPlayer doesn't throw any exceptions during construction, it would seem like the first and last line of the program are unnecessary. Am I missing something?
  • @SiddharthaShankar It's a habit - often times, you will end up with "this variable may not have been assigned" errors.
  • The null assignment and subsequent check aren't just unnecessary, they're harmful in that they turn a compile-time check into a runtime check. Without the initial assignment, any attempt to use cpu after the else clause will result in a compile-time error unless cpu had been assigned a value (in this case, one of two new instances) in all code branches. In other words, if there were ever a code branch that forgot to set value, the compiler would tell you (rather than having to throw a runtime exception).
  • @yshavit ideally, the best way to handle it would be final CpuPlayer = CpuPlayerFactory.newCpuPlayer(difficulty);
  • The factory approach seems more robust, the ternary operator would work for this specific approach only i.e. only two difficulties.