while 循环java
Java do-while loop is used to execute a block of statements continuously until the given condition is true. The do-while loop in Java is similar to while loop except that the condition is checked after the statements are executed, so do while loop guarantees the loop execution at least once.
Java do-while循环用于连续执行语句块,直到给定条件为真为止。 Java中的do-while循环与while循环类似,不同之处在于在执行语句后检查条件,因此while循环do保证循环至少执行一次。
Java做while循环 (Java do while loop)
Java do while loop syntax is as follows:
Java do while循环语法如下:
do {
// statements
} while (expression);
The expression
for the do-while loop must return a boolean value, otherwise, it will throw compile-time error.
do-while循环的expression
必须返回一个布尔值,否则将抛出编译时错误。
同时做Java流程图 (do while java flow diagram)
Java do-while循环示例 (Java do-while loop example)
Here is a simple java do-while loop example to print numbers from 5 to 10.
这是一个简单的java do-while循环示例,可打印5到10之间的数字。
package com.journaldev.javadowhileloop;
public class JavaDoWhileLoop {
public static void main(String[] args) {
int i = 5;
do {
System.out.println(i);
i++;
} while (i <= 10);
}
}
做真正的java (do while true java)
We can create an infinite loop by passing boolean expression as true
in the do while loop.
我们可以通过在do while循环中将布尔表达式传递为true
来创建无限循环。
Here is a simple do while java infinite loop example.
这是java无限循环示例。
package com.journaldev.javadowhileloop;
public class DoWhileTrueJava {
public static void main(String[] args) throws InterruptedException {
do {
System.out.println("Start Processing inside do while loop");
// look for a file at specific directory
// if found, then process it, such as inserting rows into database
System.out.println("End Processing of do while loop");
Thread.sleep(5 * 1000);
} while (true);
}
}
Note that you will have to manually quit the application to stop it, using Ctrl+C
if the program is executed in the terminal. If you execute the program in Eclipse IDE then there is a red color button to terminate the program.
请注意,如果程序在终端中执行,则必须使用Ctrl+C
手动退出应用程序以停止它。 如果您在Eclipse IDE中执行程序,则会有一个红色按钮来终止程序。
做while vs while循环 (do while vs while loop)
The only time you should use a do-while loop is when you want to execute the statements inside the loop at least once, even though condition expression returns false. Otherwise, it’s always better to use a while loop.
唯一应该使用do-while循环的方法是,即使条件表达式返回false,也要至少在循环中执行一次语句。 否则,最好使用while循环。
Java while loop looks cleaner than a do-while loop.
Java while循环看起来比do-while循环更干净。
That’s all for java do while loop. You should also look into java for loop and java continue statement.
这就是java的while循环。 您还应该研究java for loop和java continue语句 。
Reference: Oracle Documentation
参考: Oracle文档
while 循环java