Lucky Cat Tutoring Services

CIT 111: While Loops
September 17, 2009, 3:59 pm
Filed under: Uncategorized | Tags: , , , ,

While loops mean “while this statement is true, do this. When it’s false do something else. A loop is a part of a program that repeats until a certain need is met
Every “WHILE” loop that you write has certain parts. If you forget these, you can end up with an infinite loop and you don’t want this. Infinite loop goes on forever (the dreaded hourglass in windows, the spinning pinwheel of death in mac…) and THIS IS BAD! Don’t be like Microsoft, loop well.

With all loops:

Make sure not to close your loop prematurely with a “;”

while (number MAX_INT) // NO “;” IN A WHILE LOOP; && cannot work for this, instead use OR which is || {
JOptionPane.showMessageDialog(null,”You must not be able to read. Try again, Ceiling Cat is watching! “);
inData = JOptionPane.showInputDialog(” Please enter a number from 1 to 10″);
number =Integer.parseInt(inData);//make string a number datatype

Lets look at this little program:

This program demonstrates the while loop.

public class WhileLoop
//while is a KEY WORD and has special meaning. “While” is followed by a boolean expression inside a {}
//while “this bit of bode is doing its thing and this condition is true, then do this command. when it’s FALSE stop doing.

public static void main(String [] args)
int number = 1; //this INITIALIZES

while (number <= 5) //this TESTS
number++;//this UPDATES the loop

System.out.println("That's all!");

Keep in mind that {}s are your friends. They link bits of code together like putting beads in different boxes in a kit. Lets do a tracethrough of this little program: Continue reading