jeudi 25 août 2016

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?

Aucun commentaire:

Enregistrer un commentaire