while (condition) statement
while (balance < goal) {
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
years++;
}
System.out.println(years + " years.");
如果希望循环体至少执行一次,需要使用 do/while
循环将检测放在最后。语法如下:
?do statement while (condition)
do/while
种循环语句先执行语句(通常是一个语句块),然后再检测循环条件。如果为 true,就重复执行语句,然后再次检测循环条件,以此类推。
只要用户输入 “N”,循环就重复执行。这是一个需要至少执行一次的循环的示例:
Scanner in = new Scanner(System.in);
do {
double interest = balance * interestRate / 100;
balance += interest;
year++;
System.out.printf("After year %d, your balance is %,.2f%n", year, balance);
System.out.print("Ready to retire? (Y/N)");
input = in.next();
}while (input.equals("N"));
原文:https://blog.51cto.com/12185106/2580777