简体   繁体   English

java for循环以“ true”作为停止条件?

[英]java for loop with “true” as the stop condition?

I have a program I need to implement that has the following code: 我有一个需要执行的程序,该程序具有以下代码:

for (int n = 1024; true; n+=n)

I cannot find any other examples of java loops having such a format. 我找不到具有这种格式的Java循环的任何其他示例。 What does this mean? 这是什么意思? I've tried to research it, but I don't even know what to search for - it's totally foreign to me. 我已经尝试进行研究,但我什至不知道要搜索什么-这对我来说完全陌生。

The basic for statement is described in the language spec : for语句的基本描述在语言规范中

 for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement 

You are asking about the case when Expression is true . 您正在询问Expressiontrue的情况。 (The square brackets above mean it is optional). (上面的方括号表示它是可选的)。

The meaning of that is described just below, in Sec 14.14.1.2 : 含义在下面的14.14.1.2节中进行了描述

  • If the Expression is not present, or it is present and the value resulting from its evaluation (including any possible unboxing) is true, then the contained Statement is executed. 如果不存在表达式 ,或者存在表达式 ,并且其求值(包括任何可能的装箱)的结果为true,则执行所包含的Statement

... ...

  • If the Expression is present and the value resulting from its evaluation (including any possible unboxing) is false, no further action is taken and the forstatement completes normally. 如果存在表达式 ,并且其求值(包括任何可能的取消装箱)结果为false,则不会采取进一步的操作,并且forstatement正常完成。

So, Expression is present, and evaluates to true (because true evaluates to true ). 因此,存在Expression并评估为true (因为true评估为true )。 Hence, Statement is executed, and will continue to be executed because Expression remains true . 因此, Statement被执行,并且由于Expression仍然为true ,因此将继续执行。

As such, it is an infinite loop (unless there is a break, return, throw or System.exit inside the loop). 因此,这是一个无限循环(除非循环内有中断,返回,抛出或System.exit )。

Why you dont use another loop? 为什么不使用另一个循环? Use for example do-while instead of 例如使用do-while代替

for (int n = 1024; true; n+=n)

You can make a work around with: 您可以通过以下方法解决:

int n=1024;
do{ 
//your code
n+=n;
}while(condition==false);

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

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