while循环当条件为true时执行一条语句(也可以是一个语句块)。通常格式为 while(condition) statement
如果开始循环条件就为false,则循环体一次也不执行。
while循环语句首先检测循环条件。因此,循环体中的代码有坑不被执行。如果希望循环体至少执行一次,就应该将检测条件放置在最后。使用do/while循环语句。语法格式为 do statement while (condition);
这种循环语句先执行语句(通常是一个语句块),在检测循环条件;然后重复语句,在检测循环条件,以此类推。下面附上两个例子,大家自己运行一下看看:
例子一:
- import java.util.*;
- public class Retirement {
- public static void main(String[] args) {
- // read inputs
- Scanner in=new Scnner(System.in);
- System.out.print("How much money do you need to retire?");
- double goal=in.nextDouble();
- System.out.print("How much money will you contribute every year?");
- double payment=in.nextDouble();
- System.out.print("Interest rate in %: ");
- double interestRate=in.nextDouble();
- double balance=0;
- int years=0;
- // update account balance while goal isn't reached
- while(balance < goal) {
- // add this year's payment and interest
- balance +=payment;
- double interest=balance*interestRate/100;
- balance +=interest;
- years++;
- }
- System.out.println("You can retire in "+years+" years.");
- }
- }
例子二:
- import java.util.*;
- public class Retire {
- public static void main(String[] args) {
- Scanner in=new Scanner(System.in);
- System.out.print("How much money will you contribute every year?");
- double payment=in.nextDouble();
- System.out.print("Interest rate in %: ");
- double interestRate=in.nextDouble();
- double balance=0;
- int year=0;
- String input;
- // update account balance while user isn't ready to retire
- do{
- // add this year's payment and interest
- balance +=payment;
- double interest=balance*interestRate/100;
- balance +=interest;
- year++;
- // print current balance
- System.out.printf("After year %d, your balance is %, .2f%n", year, balance);
- // ask if ready to retire and get input
- System.out.print("Ready to retire? (Y/N) ");
- input=in.next();
- }
- while(input.equals("N"));
- }
- }