在Java的if语句中初始化变量? [英] Initializing a variable in an if-statement in java?

查看:165
本文介绍了在Java的if语句中初始化变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不断收到错误变量F3,可能未在您看到的最后一行代码中初始化.

I keep getting an error variable F3 may have not been intialized on the last line of code you see.

我在做什么错了?

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

推荐答案

按照 JLS :

每个局部变量和每个空白的final字段都必须有一个明确的 对其值进行任何访问时都会分配值.

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

另外来自§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.

有了代码,就有可能在F3使用之前(在代码片段的最后一行)没有任何内容分配给它.

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 = null.

这篇关于在Java的if语句中初始化变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆