while (condition) statement
while (balance < targetBalance) { years++; double interest = balance * rate / 100; balance = balance + interest; }
/** A class to monitor the growth of an investment that accumulates interest at a fixed annual rate. */ public class Investment { private double balance; private double rate; private int years; /** Constructs an Investment object from a starting balance and interest rate. @param aBalance the starting balance @param aRate the interest rate in percent */ public Investment(double aBalance, double aRate) { balance = aBalance; rate = aRate; years = 0; } /** Keeps accumulating interest until a target balance has been reached. @param targetBalance the desired balance */ public void waitForBalance(double targetBalance) { while (balance < targetBalance) { years++; double interest = balance * rate / 100; balance = balance + interest; } } /** Gets the current investment balance. @return the current balance */ public double getBalance() { return balance; } /** Gets the number of years this investment has accumulated interest. @return the number of years since the start of the investment */ public int getYears() { return years; } }
/** This program computes how long it takes for an investment to double. */ public class InvestmentRunner { public static void main(String[] args) { final double INITIAL_BALANCE = 10000; final double RATE = 5; Investment invest = new Investment(INITIAL_BALANCE, RATE); invest.waitForBalance(2 * INITIAL_BALANCE); int years = invest.getYears(); System.out.println("The investment doubled after " + years + " years"); } }
Program Run:
The investment doubled after 15 years
while (false) print("Hello"); println(" World");
waitForBalance
method would return immediately, without
entering the loopwaitForBalance
method would enter the loop once and
then returnwaitForBalance
method would throw an exceptionint years = 0; while (years < 20) { double interest = balance * rate / 100; balance = balance + interest; }
int years = 20; while (years > 0) { years++; // Oops, should have been years-- double interest = balance * rate / 100; balance = balance + interest; }
int years = 0; while (balance < 2 * initialBalance) { years++; double interest = balance * rate / 100; balance = balance + interest; } System.out.println("The investment reached the target after " + years + " years.");
year | balance | targetBalance |
0 | 10000 | 20000 |
1 | 11000 | |
2 | 12100 | |
... |
int n = 1729; int sum = 0; while (n > 0) { int digit = n % 10; sum = sum + digit; n = n / 10; } System.out.println(sum);
n | sum | digit |
1729 | 0 |
What does this loop print?
int n = 1729; String result = ""; while (n > 0) { int digit = n % 10; result = result + digit; n = n / 10; } System.out.println(result);
What does this loop print?
String greeting = "Hello"; String result = ""; int i = greeting.length() - 1; while (i > 0) { String letter = greeting.substring(i, i + 1); result = result + letter; i--; } System.out.println(result);