Initializing a variable in an if-statement in java?

空扰寡人 提交于 2020-05-16 20:59:24

问题


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

回答1:


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.




回答2:


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



回答3:


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.




回答4:


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




回答5:


Try this

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



回答6:


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.



来源:https://stackoverflow.com/questions/15275576/initializing-a-variable-in-an-if-statement-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!