Next: Using methods. Up: Expressions and loops. Previous: Comparisons.
Textbook: Section 4.6
A computer needs to be able to do something repeatedly if it's going to be useful. We can do this in Java using the while statement.
A while statement looks like the following.
For example:while(expression) statement
Say i holds 1 and n holds 23 before the computer reaches this while statement. The computer then does the following steps.while(i * 2 < n) i *= 2;
If we want to repeat a sequence of several statements, you can use braces to combine them. The computer repeatedly checks whether the condition is true and then executes all the statements listed in the braces.
Notice how we indented the body of the while loop! This isn't necessary from the Java compiler's point of view, but it's good form, to keep the program less confusing. We will deduct points if you don't adhere to good form.import csbsju.cs160.*; public class WhileExample { public static void run() { int i = 1; int n = 23; while(i * 2 < n) { i *= 2; IO.println(i); } } }
In this example, the computer would print the following.
Notice that, just before it prints 16, i*2<n is no longer true. But the computer prints the number anyway, since it checks the condition until all the statements (including the call to IO.println()) are done.2 4 8 16
One particularly popular loop arrangement is to count. You'll see this sort of thing quite a bit.
This program counts from 1 to 100.int i = 1; while(i <= 100) { System.out.print("Now I'm at "); System.out.println(i); i += 1; }
In fact, counting is so popular that Java provides some convenient abbreviations. One abbreviation is the ++ and -- operators to increment or decrement a variable.
This is slightly more convenient for those times when you want to do it.int i = 1; while(i <= 100) { System.out.print("Now I'm at "); System.out.println(i); i++; // <-- Note the change to i++ in place of i += 1 }
Next: Using methods. Up: Expressions and loops. Previous: Comparisons.