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.)
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.
"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.
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