While Loop
A while loop repeats a block of code for as long as its condition is true, which suits jobs where you don't know the number of repeats in advance.
Novice · Java · Updated
Loops are often used to process all elements in an array, but they can do more than that. We use loops to repeatedly execute a set of statements until a certain condition is met.

There are four primary types of loops in Java, each with its own use case: while, do-while, for, and for-each.
The while loop executes a block of code as long as a specified condition is true. This type of loop is particularly useful when the number of iterations is not known beforehand.
Example
This program loops indefinitely as long as the user keeps entering "yes".
import java.util.Scanner;
public class WhileLoopExample
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Do you want to run the program? (yes/no)");
String input = scanner.nextLine();
while (input.equalsIgnoreCase("yes"))
{
System.out.println("Inside the loop.");
System.out.println("Do you want to go again? (yes/no)");
input = scanner.nextLine();
}
System.out.println("Loop ended.");
}
}
In this example, the loop will continue as long as the user inputs "yes". The equalsIgnoreCase method is used to handle case sensitivity.
Do it: count the lunches your savings can buy
Your savings pay for lunch at the deli, one lunch at a time, until there isn't enough left for another. Write a function that works out how many lunches that is.
The function gets two values:
savings: the money you have now, adouble(50.0).lunchPrice: what one lunch costs, adouble(12.0). It's always more than 0.
For example, with $50 saved and $12 lunches:
| Lunch | Savings before it | Enough for it? | Savings after it |
|---|---|---|---|
| 1 | $50 | Yes | $38 |
| 2 | $38 | Yes | $26 |
| 3 | $26 | Yes | $14 |
| 4 | $14 | Yes | $2 |
| 5 | $2 | No: stop |
So lunchesYouCanBuy(50.0, 12.0) returns 4.
Your job: write the function int lunchesYouCanBuy(double savings, double lunchPrice) with a while loop.
- While
savingsis enough for one more lunch, buy it: takelunchPriceout ofsavings, and count the lunch. - Return how many lunches you bought.
- Having exactly the price is enough: $36 saved and $12 lunches buys 3.
- When
savingsis less than one lunch's price, return0.
Practiced live on the lesson page: write the Java right there and check it.