If / else / return

Hi. I’m struggling to understand the problem I’m having with IF (than) ELSE IF (than) RETURN at the end.
In Medieval Game, the last exercise in Java Serialization Course, I tried to solve problem with IF/ELSE IF statements, but at the end I have error problem with return statement “error: variable player might not have been initialized return player;”

Can anyone help me understand what I’m doing wrong? I saw it’s doable with “while” statement, but I wanted to try and solve it with IF/ELSE IF. Is it even possible to do it this way?

Thanks in advance.

private Player start(Scanner console) { // Add start functionality here Player player; System.out.println("Welcome to Medieval Game!"); System.out.println("Would you like to start a new game or load a saved game? \n Enter \"y\" for Yes and \"n\" to load saved game: "); String answer = console.next().toLowerCase(); if (answer != "y" && answer != "n") { System.out.println("Please enter \"y\" for Yes and \"n\" for No!"); } else { if (answer == "y") { System.out.println("Type your new name: "); String newName = console.next(); player = new Player(newName); } else if (answer == "n") { System.out.println("Type your name: "); player = load(console.next(), console); } } return player; } // End of start

The problem you’re having is if the user inputs something that isn’t ‘y’ or ‘n’ the code will get to the end and try to return ‘player’ without it being initialized.
The while loop meant the code was effectively stuck in an infinite loop until a valid input was used - whereupon player would be initialized, either as new or the loaded game.

Hope that helps.


Now I can see where the problem lies and why the “while” condition is more suitable.
Thank you for your answer and help.

1 Like