Mathyou Mathyou - 3 months ago 12
Java Question

Local variable error in "if" statement (Java)

import java.util.Scanner;
import java.util.Random;
import static java.lang.System.out;

class TestingStuf {
enum tooWhat {tooHigh, tooLow, justRight};

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random myRandom = new Random();

tooWhat guess;

out.println("Pick a number between 1 and 10.");
int userGuess = keyboard.nextInt();
int randomNumber = myRandom.nextInt(10) + 1;

if (userGuess < randomNumber) {
guess = tooWhat.tooLow;
}else if (userGuess > randomNumber) {
guess = tooWhat.tooHigh;
}else if (userGuess == randomNumber) {
guess = tooWhat.justRight;
}

out.println("Your guess is:");

if (guess == tooWhat.tooLow) {
out.println("Too low.");

}else if (guess == tooWhat.tooHigh) {
out.println("Too high.");

}else if (guess == tooWhat.justRight) {
out.println("Correct!");

}

keyboard.close();
}
}


In my code I have an error in the second set of "if" statements that says The "local variable guess may not have been initialized" even though in the previous "if" statement I give the "guess" variable a value that is dependent on the user input. What am I doing wrong?

Answer

If you look at your code, it seems like there's a path through the if...else if...else if where guess is never initialized. That's what the compiler is warning you about, because code subsequent to that expects that guess will definitely have a value.

Although we, as humans, know that your three conditions are mutually-exclusive, the compiler isn't quite as smart as we are. Just make your final one an else rather than an else if (...):

if (userGuess < randomNumber) {
    guess = tooWhat.tooLow;
}else if (userGuess > randomNumber) {
    guess = tooWhat.tooHigh;
}else { // *** No `if`
    guess = tooWhat.justRight;
}
Comments