运行此代码时可以期待什么行为:
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做一会儿,一会儿
发布评论