While Loops (page 1)

There are two types of loops: for loops and while loops. Some languages have a couple of variations on the while loop (e.g. until, do while).


Description Syntax Example
Normal while loop
This only executes if the condition is true
while (condition) {
while (lives > 0) {
Infinite loop: while

Infinite loop: for
while (true) {

for (;;) {
Do While loop
This always executes at least once.
do {
} while (condition);
boolean done = false;
do {
   num = myScanner.nextInt();
   if (num > 0) done = true;
} while (!done);

Note that in the do-while format, you MUST end the last line with a ; (semicolon).
Remember: all lines must end in { } or ;


public static void main(String[] args) {
   int n=0;
   while (n < 15) {
      System.out.println(n + " still looping ...");
   System.out.println("loop is over");

Break, Continue, and other ways of exiting loops

I've written about this in the page on for loops
Basically, . . . break; exits the loop,
continue; stops that iteration of the loop and goes back to the top.
You can also exit while loops by making the loop test condition false.


import java.util.Scanner;
/* Program to add up to 100
  by Mr. Harwood
  Sept 18, 2014
public class WhileLoop {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int num, count, total;
		total = count = 0;
		while (total < 100) {
			System.out.print("Type in a number: ");
			if (sc.hasNextInt()) { 	//check for "int"				
				num = sc.nextInt();				
			} else {	//get rid of junk (rest of line)
				continue;	//go to beginning of loop
			if (num > 100) continue; //no numbers more than 100
			if (num < 0) break; //stop loop immediately for negative numbers
			if (num == 0) System.exit(0); //terminate!
			total += num;
		System.out.printf("Your total is %d, after %d numbers",total,count);


READ THIS! you should never use System.exit(0) unless you have a very specific and good reason to do so. It is not good programming technique and should be avoided.
If this were an important program, I'd write this instead: if (num == 0) return . This is a better way, but we haven't learnt about "return" yet.

While loops page 2