简体   繁体   中英

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.

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.

The following code is equivalent to your if/if statements:

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 :

Each local variable and every blank final field must have a definitely assigned value when any access of its value occurs.

Additionally from §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).

Use 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. Because of your if conditions there might be a case that this variable won't be assigned any value

尝试这个

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 statement is better for human and compiler. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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