Java 变量不会在 if 语句中初始化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19486957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:41:07  来源:igfitidea点击:

Java Variable will not initialize in an if statement?

java

提问by WeekzGod

I have initialized and declared the variable "average." I do not understand why it won't compile. Does it have to do with the fact that it's in an if else? I've already tried "|| null" and that is not taking either. What to do?

我已经初始化并声明了变量“平均”。我不明白为什么它不会编译。这与它在 if else 中的事实有关吗?我已经尝试过“|| null”,但也没有尝试过。该怎么办?

 // declare variables
    Scanner keyboard = new Scanner (System.in);
    String given;
    String middle;
    String sur;
    String truefalse;
    boolean bool;
    int exam1;
    int exam2;
    int exam3;
    double average;

    // get input
    System.out.println("***************  Grade Computer *************");
    System.out.println("Enter the student's first name: ");
    given = keyboard.nextLine();

    System.out.println( "Enter the student's middle initial: ");
    middle = keyboard.nextLine();

    System.out.println( "Enter the student's last name: ");
    sur = keyboard.nextLine();

    System.out.println( "Enter EXAM 1 Grade: ");
    exam1 = keyboard.nextInt();

    System.out.println( "Enter EXAM 2 Grade: ");
    exam2 = keyboard.nextInt();

    System.out.println( "Enter EXAM 3 Grade: ");
    exam3 = keyboard.nextInt();

    keyboard.nextLine();
    System.out.println( "Bonus work completed [true/false]");
    truefalse = keyboard.nextLine();

    // adjust exam scores if necesssary
    if (truefalse == "true")
    {
        bool = true;
        exam1 = keyboard.nextInt();
        exam2 = keyboard.nextInt();
        exam3 = keyboard.nextInt();
    }
    else
    {
        average = ((exam1+exam2+exam3)/3);  
    }   

Why is the compiler saying "variable average might not have been initialized"?

为什么编译器说“变量平均值可能尚未初始化”?

回答by dtgee

You need to initialize average. The compiler is complaining because your code might or might not ever reach the elseblock. Yet, if you use averagewhen it hasn't been initialized, you get an error.

您需要初始化average. 编译器抱怨是因为您的代码可能会也可能不会到达该else块。但是,如果average在尚未初始化的情况下使用,则会出现错误。

double average = null;

Alternatively, you can initialize averagein the ifblock as well, because if the ifblock runs and the elsedoesn't you'll still have an initialized averageat the end of the day and the compiler is happy :).

或者,您也可以averageif块中进行初始化,因为如果if块运行而else没有运行,您仍然会average在一天结束时进行初始化并且编译器很高兴:)。

if (truefalse == "true")
{
    average = //something;
    bool = true;
    exam1 = keyboard.nextInt();
    exam2 = keyboard.nextInt();
    exam3 = keyboard.nextInt();
}
else
{
    average = ((exam1+exam2+exam3)/3);  
}   

Also, as a final note, a good rule of thumb is to use .equals()for any Stringand ==for ints, characters, booleans etc.

此外,作为最后一点,一个好的经验法则是.equals()用于任何String==整数、字符、布尔值等。

回答by GraphicsMuncher

  • You declared your variable but did not strictly initialize it. It is onlyinitialized if the logic of your program dictates that the line average = ((exam1+exam2+exam3)/3);is hit. This doesn't happen if truefalse == "true".

  • In order to have Java compile it, you can do one of two things.

    1. Initialize your variable to some default value when you declare it, eg double average = 0;

    2. Make sure that no logical pathway precludes the possibility that the variable is initialized. That is, no matter whathappens, it gets initialized.

  • 您声明了变量但没有严格初始化它。当您的程序逻辑指示该行average = ((exam1+exam2+exam3)/3);被命中时,它才会被初始化。如果truefalse == "true".

  • 为了让 Java 编译它,你可以做两件事之一。

    1. 声明变量时将变量初始化为某个默认值,例如 double average = 0;

    2. 确保没有逻辑路径排除变量被初始化的可能性。也就是说,不管什么情况,它就会被初始化。

The first option is better. It keeps your code cleaner and more logical, thus easier to maintain. The second option is more implicit than explicit. You probably shouldn't have to go walking through the logic yourself to see how it works out.

第一个选项更好。它使您的代码更清晰、更合乎逻辑,从而更易于维护。第二个选项比显式更隐式。您可能不必亲自遍历逻辑来查看它是如何工作的。

回答by samadhiya8

You can initialize the double variable average to 0 when you are declaring it.

您可以在声明时将双变量平均值初始化为 0。

double average=0;

双平均=0;

Reason of this particular error is that you are trying to initialize the variable in if-else block. The variable will not be initialized if condition is not true. If you are using the variable further in your program, you will get run time errors. That is why Java compiler is letting you know that there are possibilities that the variable mightbe uninitialized

此特定错误的原因是您试图在 if-else 块中初始化变量。如果条件不为真,变量将不会被初始化。如果您在程序中进一步使用该变量,则会出现运行时错误。这就是为什么 Java 编译器让您知道变量可能未初始化的原因

Furthermore it is always a good practice to initialize a local variable when you declare it.

此外,在声明局部变量时初始化它始终是一个好习惯。