【问题标题】:"unreachable statement" when trying to compile a "while" statement尝试编译“while”语句时的“unreachable statement”
【发布时间】:2012-11-18 05:50:25
【问题描述】:

我是 Java 新手,正在完成一些课程作业。但是,在下面的代码中,我在尝试编译时收到错误“Unreachable statement”。关于我做错了什么的任何指示?

public String getDeliveredList() {
   int count = 0;
   while (count < deliveredList.size()){
       return ("Order # " + count + deliveredList.get(count).getAsString());
       count++;
   }
}

【问题讨论】:

  • 退货声明后不能有声明。它永远不会被执行,因为它无法访问(你的代码已经从方法返回了执行)

标签: java while-loop unreachable-statement


【解决方案1】:

从函数返回后,从逻辑上讲,在此之后它不能再执行任何操作——永远不会到达count++ 语句。

while (count < deliveredList.size()){

   // function always ends and returns value here
   return ("Order # " + count + deliveredList.get(count).getAsString());

   // this will never get run
   count++;
}

【讨论】:

  • 是的,并且该例程将最多执行一次(部分)迭代。 if (count &lt; deliveredList.size()) 也可以。
  • dbaseman 是对的。你应该在 return 语句之前尝试count++;,如果这仍然适用于你正在尝试做的事情。
【解决方案2】:

如果你从一个函数返回,那么在函数返回点之后的任何语句基本上都是无法访问的语句,编译器会在这些语句上发出错误。

但是,尽管在 return 之后编写了语句,但以下代码不会发出错误

void max(int a,int b)
{
    if(a>b) 
    {
        System.out.println(a+" is greater");
        return;
    }

    System.out.println(b+" is greater");
    return;
}

这是因为第一个 return 语句是在嵌套范围内编写的,并且在函数范围内不会立即可见。当 a>b 时,程序执行只会通过第一个 return 语句。如果不是这样,则永远不会执行该代码块。因此,尽管返回后有语句,但代码是可编译的;

【讨论】:

    猜你喜欢
    • 2012-07-30
    • 2016-07-25
    • 2022-01-03
    • 2016-01-15
    • 2020-10-09
    • 2011-07-25
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多