简体   繁体   English

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

[英]Initializing a variable in an if-statement in java?

I keep getting an error variable F3 may have not been intialized on the last line of code you see. 我不断收到错误变量F3,可能未在您看到的最后一行代码中初始化。

What am I doing wrong? 我究竟做错了什么?

{
    Float F1,F2, F3;

    F1 = Float.parseFloat(
      JOptionPane.showInputDialog("Enter a number and press ok."));


    F2 = Float.parseFloat(
      JOptionPane.showInputDialog("Enter a second number and press ok."));

    if(F1 >= F2)
    {

      F3=(F1 * F2) + (F1 * 2);
    }
    if(F2 >= F1)
    {
      F3 =(F1 + F2) + (F2 * 5);
    }

     DecimalFormat dec = new DecimalFormat("##.##");


  JOptionPane.showMessageDialog(null,"Your calculations are:" +(F3),"Caculations", JOptionPane.INFORMATION_MESSAGE);

You should probably use if/else instead of if/if here, so that the compiler knows that F3 will always be set to a value. 您可能应该在此处使用if / else而不是if / if,以便编译器知道F3将始终设置为一个值。

The following code is equivalent to your if/if statements: 以下代码等效于您的if / if语句:

if(F1 > F2) //The = here will always be overridden by the other if clause in your original statement so it's redundant.
{ 
  F3=(F1 * F2) + (F1 * 2);
}
else
{
  F3 =(F1 + F2) + (F2 * 5);
}

As per JLS : 根据JLS

Each local variable and every blank final field must have a definitely assigned value when any access of its value occurs. 每个局部变量和每个空白的final字段在对其值进行任何访问时都必须具有一个明确分配的值。

Additionally from §14.4.2 : 从第14.4.2节开始

If a declarator does not have an initialization expression, then every reference to the variable must be preceded by execution of an assignment to the variable, or a compile-time error occurs. 如果声明器没有初始化表达式,则对变量的每个引用都必须在对变量的赋值之前执行,否则会发生编译时错误。

With the code there, it is possible that nothing ever gets assigned to F3 before it is used (in the last line of the code snippet). 使用此处的代码,有可能在使用F3之前(在代码片段的最后一行)没有任何内容分配给F3

Use F3 = null . 使用F3 = null

Your code is equivalent to: 您的代码等效于:

if(F1 > F2) {
  F3 = (F1 * F2) + (F1 * 2);
} else {
  F3 = (F1 + F2) + (F2 * 5);
}

This should make the error go away. 这应该使错误消失。

When you declare a variable F3 assign null to it. 声明变量F3时,请为其分配空值。 Because of your if conditions there might be a case that this variable won't be assigned any value 由于您的if条件,可能会导致此变量不会被分配任何值

尝试这个

Float F1=0,F2=0, F3=0;

The best way is to use if-else statement and do NOT assign null to the variable. 最好的方法是使用if-else语句,并且不要将null赋给变量。 If-else statement is better for human and compiler. If-else语句更适合人类和编译器。 Assigning null is meaningless and makes compiler unable to check uninitialized problem for your future modifications and then you may get NullPointerException if you don't check it. 分配null是没有意义的,并且使编译器无法检查未初始化的问题以进行将来的修改,如果不进行检查,则可能会收到NullPointerException。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM