While之后无法访问的语句 [英] unreachable statement after while

查看:0
本文介绍了While之后无法访问的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在修改代码,在以下代码中遇到错误:

    int x=1;
    System.out.println("x "+x);
    while (true)    {
        x++;
    }
    System.out.println ("x "+x);

错误在最后一行。我可以知道错误(Error:Unreacable语句)是什么意思吗?

另外,我如何修改代码,使x的值在内部增加,而循环不更改全局值,以及哪些修改将更改全局值?

推荐答案

我可以知道错误(Error:Unreacable语句)是什么意思吗?

这意味着编写的代码毫无用处,因为它将不会被执行,因为前面行的(代码)语句永远不会从方法中出来或返回,在以下情况下会发生这种情况:

(1)无限循环或迭代(如while(true)for(;;))

public R method() {
  while(true) { //infinite loop
    //some code
  }
  //from here the below code will never get executed
}

这就是您的情况,您的代码x++;将永远运行,永远不会退出while循环。

(2)在此之后抛出异常时,代码语句将不会执行,如下所示:

public R method() {
  //some code
  throw new MyException(" Exception is ... ");
  //from here code is unreachable
}

(3)使用显式return语句

public R method() {
      //some code
      return r;
      //from here code is unreachable
    }

这篇关于While之后无法访问的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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