Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble instantiating an object within an if block

Tags:

java

scope

I've written a program where users can choose between two games to play: Pig or Snake. I tried to use the following code within my main method to create the appropriate kind of game:

if (gameType == 'p')
    PigGame game = new PigGame();
else
    SnakeGame game = new SnakeGame();

My compiler points to the second line and gives the error: not a statement

I have managed to fix the problem by writing an abstract class "Game" and then making PigGame and SnakeGame subclasses of it:

Game game;
if (gameType == 'p')
    game = new PigGame();
else
    game = new SnakeGame();

But I don't understand why the first construct didn't work. (I'm preparing to teach a high school programming course, but I'm new to Java and OOP so I can use any insights you can provide.)

like image 808
user2625004 Avatar asked Mar 23 '23 20:03

user2625004


2 Answers

The problem is that the scope of game is inside the if and the else

if (gameType == 'p')
    PigGame game = new PigGame();
else
    SnakeGame game = new SnakeGame();

So you can't use it anywhere else, that's why your second piece of code works.

like image 130
jsedano Avatar answered Mar 31 '23 21:03

jsedano


"PigGame game = new PigGame();" is a declaration, not a statement. An if requires a statement, not a declaration. You could create a statement block containing it:

{
    PigGame game = new PigGame();
}

That would be syntactically correct. It would still be pointless, because game would be local to the statement block. You need game to be declared with a wider scope.

like image 24
Patricia Shanahan Avatar answered Mar 31 '23 19:03

Patricia Shanahan