Java做一会儿,一会儿 [英] Java do while, while
问题描述
运行此代码时可以期待什么行为:
what behaviour can I expect when I run this code:
do while(testA) {
// do stuff
} while(testB);
它将表现为:
do {
while(testA) {
// do stuff
}
} while(testB);
或者:
if(testA) {
do {
// do stuff
} while(testA && testB);
}
还是完全出乎意料的事情?
Or something totally unexpected?
我之所以问这个问题,是因为我认为这很模棱两可,对于其他正在搜索此主题的人来说,不是,因为我懒于对其进行测试.
I ask this question because I think this is quite ambiguous, and for other people searching on this topic, not because I am lazy to test it out.
推荐答案
它等效于您的第一个块:
It is equivalent to your first block:
do {
while(testA) {
// do stuff
}
} while(testB);
Java语法解析时为:
DoStatement:
do Statement while ( Expression ) ;
Statement:
WhileStatement
WhileStatement:
while ( Expression ) Statement
Statement:
Block
Block:
{ BlockStatements_opt }
您可以看到Java编译器会将其解析为do <WhileStatement> while ( Expression ) ;
.这是解析您编写的代码的唯一有效方法.
You can see that the Java compiler will parse this as do <WhileStatement> while ( Expression ) ;
. That's the only valid way to parse the code that you wrote.
请记住,解析此构造没有任何特殊规则.由于do-while循环的编写方式不寻常,这最终使人难以理解.在正常使用情况下,do-while总是写为do { ... } while
并带有大括号.
Keep in mind that it doesn't have any special rule to parse this construct. It just ends up being confusing for a human to read due to the unusual way the do-while loop is written. In normal usage do-while is always written as do { ... } while
with explicit curly braces.
这篇关于Java做一会儿,一会儿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!