【问题标题】:My Return Statement is Unreachable我的退货声明无法访问
【发布时间】:2015-10-17 06:01:40
【问题描述】:
public BigDecimal calculateTotal() {
    BigDecimal percent = BigDecimal.valueOf(0.9);
    int i = 0;
    BigDecimal price = BigDecimal.valueOf(0.0);
    while(!myOrders.isEmpty()){
        if (!myOrders.get(i).getItem().isBulk() && myMembership == true){
            price = price.add(myOrders.get(i).calculateOrderTotal().multiply(percent));
            myOrders.remove(i);
        }
        else{
            price = price.add(myOrders.get(i).calculateOrderTotal());
            myOrders.remove(i);
        }
    }
    //WHY IS THIS UNREACHABLE?!
    return price.setScale(2, RoundingMode.HALF_EVEN);
}

我知道 return 语句之后的任何代码都是无法访问的代码,但我唯一的 return 语句是无法访问的,我不知道为什么。 while 循环是这样的,因为我正在抓住稻草,我知道它可能不会做我想要它做的事情。 myOrders 是一个 ArrayList。

【问题讨论】:

  • 这里的 myOrders 变量到底是什么? (数据类型)
  • 编译器是说它无法访问还是您只是无法访问它?
  • 编译器说它无法访问。我正在使用日食。
  • 我看不出有什么原因。也许尝试在eclipse中清理项目。
  • 如果解决了你的问题,请将对应的答案标记为solution,这样以后的读者可以很容易地找到解决方案。

标签: java return unreachable-code


【解决方案1】:

编辑:既然 OP 说它是ArrayList,我的回答不再适用。

您永远不会更新您的索引i。这应该有效:

public BigDecimal calculateTotal() {
    BigDecimal percent = BigDecimal.valueOf(0.9);
    int i = 0;
    BigDecimal price = BigDecimal.valueOf(0.0);
    while(!myOrders.isEmpty()) {
        if (!myOrders.get(i).getItem().isBulk() && myMembership == true) {
            price = price.add(myOrders.get(i).calculateOrderTotal().multiply(percent));
            myOrders.remove(i);
        } else {
            price = price.add(myOrders.get(i).calculateOrderTotal());
            myOrders.remove(i);
        }
        i++;    // <-- You were missing this
    }
    // Not unreachable anymore :)
    return price.setScale(2, RoundingMode.HALF_EVEN);
}

【讨论】:

  • OP 说该对象是一个 ArrayList,并且由于 ArrayLists 会在删除元素时自动重新排列,因此索引没有增加应该无关紧要。
【解决方案2】:

您的变量i 永远不会增加。根据myOrders是什么类型的集合,每次移除第0个元素可能不会移动集合中的元素,myOrders永远不会为空。

【讨论】:

  • Depending on what type of Collection "myOrders" is 这是最好的选择。 +1
  • myOrders 是一个 ArrayList。增量不会改变错误。这是我尝试的第一件事。
【解决方案3】:

发布的代码中没有任何内容可以解释该错误。 既然你说你的IDE是Eclipse,我建议清理项目。 此外,请确保在查看此错误之前修复所有其他错误。 这个错误没有意义, 我怀疑您的项目中还有其他编译器错误, 这以某种方式导致这是一个奇怪的副作用。 其他的都修好后,这个自然就消失了。

顺便说一句,为了看得更清楚,这是相同代码的清理版本,做的事情完全相同:

BigDecimal percent = BigDecimal.valueOf(0.9);
BigDecimal price = BigDecimal.ZERO;

while (!myOrders.isEmpty()) {
    Order first = myOrders.get(0);
    BigDecimal subtotal = first.calculateOrderTotal();
    if (!first.getItem().isBulk() && myMembership) {
        subtotal = subtotal.multiply(percent);
    }
    price = price.add(subtotal);
    myOrders.remove(0);
}
return price.setScale(2, RoundingMode.HALF_EVEN);

【讨论】:

    【解决方案4】:

    清理eclipse解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2021-09-01
      • 2011-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-04
      • 2013-07-11
      • 2022-11-18
      • 2017-06-06
      相关资源
      最近更新 更多