【问题标题】:if (boolean)unreachable statement in JavaJava 中的 if (boolean)unreachable 语句
【发布时间】:2016-06-02 07:16:57
【问题描述】:

这是我正在学习的入门编程课程。我创建了一个实例方法来将newValue 添加到总数中。 它在方法中有两个参数: (识别金额类型和金额的字母) 我在第一个参数上成功了。 第二个是让我挣扎。我假设我们有一个 if 语句。我做到了,所以有金额类型,然后我有三个要使用的字母可以是真的。我设置了if(amountType == false),编译器说它是“无法访问的语句”。 if 语句的标准是“如果金额的字母无效(即不是 T、D 或 E),则抛出 IllegalArgumentException,并将消息返回给用户。

public double newValue(boolean amountType, double amount)
{
  boolean T = amountType;
  boolean D = amountType;
  boolean E = amountType;


    if (amount < 0) 
    {
  throw new IllegalArgumentException("The amount needs to be 0 or larger");
    }
    return amount;



    if(amountType == false)
        // if not D, E, T.....then exception
    {
        throw new IllegalArgumentException("That is an invalid letter value. "
                + "The data will be ignored");
    } 
    else
    {
    }
}    

任何帮助将不胜感激。

【问题讨论】:

  • return amount; 将控制流移动到您的方法之外,因此没有必要在其后添加任何代码,因为它不会被执行(这将是死代码)。
  • 拥有returned 后您将无法拥有代码,因为它永远不会被调用。如果您想继续,请不要返回。

标签: java if-statement unreachable-statement


【解决方案1】:

你的return 语句妨碍了:一旦执行,之后的任何代码都不会被执行。它必须是在您的方法中执行的最后一条指令(不是字面意思)。你可以这样做:

public double newValue(boolean amountType, double amount) {
    boolean T = amountType;
    boolean D = amountType;
    boolean E = amountType;


    if (amount < 0) // Eliminate constraint 1
        throw new IllegalArgumentException("The amount needs to be 0 or larger");

    if (!amountType) // Eliminate constraint 2
        throw new IllegalArgumentException("That is an invalid letter value. "
                + "The data will be ignored");

    // Do your processing, now that you passed all tests

    return amount;
}

【讨论】:

  • 谢谢。我在想我可以为每个 if/statement 获得回报。
  • 不客气@Luke8h。这样,一个return 语句就可以了。
【解决方案2】:

您必须将 return amount 放在第一个 if 块内。

原因是如果第一个if 条件是true 则会抛出异常。如果它被评估为false,则return amount将被执行。

在这两种情况下,第二个if 块将永远不会被执行

【讨论】:

  • 任何解释是什么问题,为什么你认为这会解决它?
  • 第二个if永远不会被执行,因为抛出了异常(amount&lt;0)或者返回了amount
  • @IsidroGH 您应该将该评论添加到答案中。因为所有答案都应包括解释或以某种方式支持答案。
  • 是的,你的英文思维比我快:)
【解决方案3】:

Unreachable 表示此方法永远无法到达该线路。 因为您添加了没有 if 语句的 return 语句,所以您的第二个 if 语句永远不能被程序执行。 所以在你的第一个 if 语句中移动 return 语句,它会起作用。

【讨论】:

    【解决方案4】:

    你有一个 return amount 语句,它总是执行并且它之后的代码,即 if 语句不可访问,因为控件总是从 return amount 返回。 一种可能的解决方案是,首先您必须检查金额类型,然后在 else 部分检查金额

    【讨论】:

      猜你喜欢
      • 2016-01-15
      • 2013-05-21
      • 2016-07-25
      • 1970-01-01
      • 2015-11-09
      • 1970-01-01
      • 2018-08-12
      • 1970-01-01
      • 2014-10-29
      相关资源
      最近更新 更多