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

时间:2016-08-25 22:55:27

标签: java variables if-statement local-variables

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”语句中出现错误,即“本地变量猜测可能尚未初始化”,即使在之前的“if”语句中我给“guess”变量赋值这取决于用户输入。我做错了什么?

3 个答案:

答案 0 :(得分:2)

如果您查看代码,似乎就像if...else if...else ifguess从未初始化guess的路径一样。这就是编译器警告你的内容,因为在此之后的代码期望else肯定会有一个值。

虽然我们作为人类知道你的三个条件是相互排斥的,但编译器并不像我们那样聪明。只需将最后一个设为else if (...)而不是if (userGuess < randomNumber) { guess = tooWhat.tooLow; }else if (userGuess > randomNumber) { guess = tooWhat.tooHigh; }else { // *** No `if` guess = tooWhat.justRight; }

    Parallel.ForEach(guidDictionary, (dictionaryItem) =>
    {
        var fileName = dictionaryItem.Key;
        var fileText = File.ReadAllText(fileName, Encoding.ASCII);
        Parallel.ForEach(guidDictionary, (guidObj) =>
        {
            fileText = fileText.Replace(guidObj.Value.OldGuid, guidObj.Value.NewGuid);
        });

        File.WriteAllText(fileName, fileText);
    });

答案 1 :(得分:0)

将您的最后一条if else语句更改为else语句

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

这样编译器就知道猜测不可能保持未初始化。

答案 2 :(得分:0)

编译器不确定是否应该根据if..else if..else..if梯形图提供变量值。如果编译器要评估每个梯形步骤的值,那么它将能够找到它,但这对编译器来说是一种过度杀伤力。按照代码进行操作,如果使用else,则替换最后的其他内容将解决您的问题。