2015-09-28 54 views
-1

有人可以让我知道一些资源在线,定义为这种奇怪的实时行为?do-while在底部声明

int i = 0; 
do while (++i < 1) { //this compile (?!?) 
     System.out.print("i is " + i); 
} 

do while (++i < 1) // this compile also 
     System.out.print("i is " + i); 
do while (i > 1) {} 

while (i > 1) {} //this doesn't compile, the comp. wants the semicolon 

对不起,我错过了do-while语句的内容?

在此没有提及在所有Oracle官方链接: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

编辑: 对不起,我解释的嵌套,而作为另一个语句。

这是困惑我原来的语句:

int i = 1; 
do while (i < 1) 
System.out.print("i is " + i); 
while (i > 1); 

这编译...,等同于:

do { 
    while (++i < 1) // this compile also! 
    System.out.print("i is " + i); 
} 
while (i > 1); 
+3

我怀疑',而(I> 1){}'doesn't如果'i'存在编译... – SomeJavaGuy

+1

其实'while(i> 1){}'是唯一可以编译的循环。 – stevecross

+0

你发布的内容不能编译,你在'while(...)之后丢失了一个分号;'我建议你阅读JLS:https://docs.oracle.com/javase/specs/jls/se8/ html/jls-14.html#jls-14.13 – Tunaki

回答

1

在您发布的神谕链接是所有解释:

The Java programming language also provides a do-while statement, which can be expressed as follows: 

do { 
    statement(s) 
} while (expression); 

如果我将您的代码复制到我的IDE(Eclipse)上,这里是我的结果:

int i = 0; 
do while (++i < 1) { //DO NOT COMPILE,Syntax error, insert "while (Expression) ;" to complete DoStatement 
     System.out.print("i is " + i); 
} 

do while (++i < 1) // DO NOT COMPILE,Syntax error, insert "while (Expression) ;" to complete DoStatement 
     System.out.print("i is " + i); 

while (i > 1) {} //COMPILE 
do while (i > 1) {} //DO NOT COMPILE,Syntax error, insert "while (Expression) ;" to complete DoStatement 
0

我不确定你在问什么。

while(i>1){}//this doesn't compile. 

这是正确的语法。

也为代码DO-而行正确的说法是

do { 
    //code goes here 
} while (i > 1); 

我想我应该指出的是,一个做而行代码会做的括号内的代码不管,然后检查是否需要重复。然而,while语句将检查它是否i> 1,如果为true,它将运行代码。

希望这会有所帮助。

0

虽然语法不正确。 在简单的方法,你应该这样想这个 - >做一些事情,直到(条件) 所以这里是语法

do{ 
//statement 
}while(condition is true);