"if" 语句中的局部变量错误 (Java)

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();
    }
}

在我的代码中,我在第二组 "if" 语句中有一个错误 "local variable guess may not have been initialized" 即使在之前的 "if" 语句中我给出了 "guess"变量 取决于用户输入的值。我做错了什么?

如果您查看您的代码,似乎 有一条通过 if...else if...else if 的路径,其中 guess 从未被初始化。这就是编译器警告您的内容,因为随后的代码预计 guess 肯定会有一个值。

虽然作为人类,我们知道您的三个条件是互斥的,但编译器并不像我们那么聪明。只需将您的最后一个设为 else 而不是 else if (...):

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

将最后一个 if else 语句更改为 else 语句

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

这样编译器就知道 guess 不可能保持未初始化状态。

编译器不确定是否应该根据仅通过 if..else if..else..if 阶梯为变量 guess 提供一个值。如果编译器要评估每个阶梯步骤的值,它就能够找出来,但这对编译器来说太过分了。按照代码,将 last else if 替换为 else 将解决您的问题。