private int getJobIndex() {
int jobNum;
boolean inputValid = false;
while (!inputValid) {
jobNum = getIntegerInput("Please select a job to work on: ");
if (jobNum < 0 || jobNum >= game.getNumberOfJobs()) {
System.out.println("Invalid selection. Please choose a valid job.");
}
else {
inputValid = true;
}
}
return jobNum;
}
This is a somewhat theoretical question, so please bear with me. In the code above, I'm getting user input, validating it in a loop, and returning it. The code as written above does not compile in Eclipse, because "The local variable jobNum may not have been initialized". Eclipse' suggestion is to change the initial declaration to int jobNum = 0;
. This bothers me, though, because if jobNum got past the while loop without being initialized, that would be bad, and it being set to 0 would potentially make that bug very hard to find (especially so here, because 0 is a valid job index). If it was uninitialized, I imagine things would break pretty quickly, and I'd find the bug. Now, I could initialize it to -1, but it's easy to imagine a similar scenario where all ints are valid. It doesn't really matter for this example, but in the interest of writing better code in the future...
So in summary, I have two questions:
- Why does Eclipse force this on me? It seems like a pretty heavy-handed compiler error.
- What is the correct way to code this that doesn't introduce a default value that I might easily mistake for input?