繁体   English   中英

为什么说我的If语句无法访问?

[英]Why is it saying my If statement is unreachable?

编译器说该语句在if语句的行上不可访问。 我对Java不太熟悉。

public double calculate()
{
  total_usage_charge = getUsageCharge();
  total_charge = rate + total_usage_charge;

  return total_charge;

  if("A".equals(package_plan.toUpperCase()) && getUsageCharge() > 14.95)
  {
    sB = getUsageCharge() - 14.95;
    System.out.println("You're spending more money than you should. If you switched to Plan B you would save:$" + sB);
  }
}

因为您要通过执行以下操作从方法中返回:

return total_charge;

因此,下一条语句将永远不会执行。

您从if语句之前的方法返回( return total_charge; )。 return之后无法执行任何代码(如果return语句位于try...catch...finally则相关的finally块除外)。

您将在调用if语句之前返回,因此它无法到达。

当方法到达return语句时,该方法返回到调用它的代码。

return total_charge;

您的方法此时返回,发布任何代码都将无法访问。

您已将返回声明放在IF上方。 因此,当编译器每次从那里返回时都使用此语句时,如果任何时候都无法执行,则删除return语句,或者将它放在Condition下方。

返回语句后将不执行代码。以下代码块引起问题,即

return total_charge;

因此,您将必须删除此行或将其放在末尾。

public double calculate()
{
  total_usage_charge = getUsageCharge();
  total_charge = rate + total_usage_charge;

  if("A".equals(package_plan.toUpperCase()) && getUsageCharge() > 14.95)
  {
    sB = getUsageCharge() - 14.95;
    System.out.println("You're spending more money than you should. If you switched to Plan B you  would save:$" + sB);
  }

  return total_charge;
}

就像那样;)

**if("A".equals(package_plan.toUpperCase()) && getUsageCharge() > 14.95)
        {
            sB = getUsageCharge() - 14.95;
            System.out.println("You're spending more money than you should. If you switched to Plan B you would save:$" + sB);
        }
        else if("A".equals(package_plan.toUpperCase()) && getUsageCharge() > 19.95)
        {
            sC = getUsageCharge() - 19.95;
            System.out.println("You're spending more money than you should. If you switched to Plan C you would save:$" + sC);
        }
        else if("B".equals(package_plan.toUpperCase()) && hours < 10)
        {
            sA = getUsageCharge() - 9.95;
            System.out.println("You're spending more money than you should. If you switched to Plan A you would save:$" + sA);
        }
        else if("B".equals(package_plan.toUpperCase()) && getUsageCharge() > 19.95)
        {
            sC = getUsageCharge() - 19.95;
            System.out.println("You're spending more money than you should. If you switched to Plan C you would save:$" + sC);**
        }**

您是否打算发表评论,如果是,请正确。 或根据提供的代码,这是错误且无法访问的声明。

使用/* your code to comment */注释它/* your code to comment */

暂无
暂无

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

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