CSC152 2005F, Class 18: Loops Admin: * Read "Separating What from How: Interfaces in Java" (and yes, it's ready) * I've made significant changes to the next few weeks of the schedule. * Thanks for the editing of the readings * Attending football games; attending soccer games; attending x-country; basketball meets earns you extra credit * Attending swing dances earns you extra credit (Nov. 4) * Questions on the exam? * Eryn will be available to answer general questions (e.g., on the Exceptions lab you did not complete) Tuesday from 7-8 p.m. Overview * Quick overview * Lab /Exam Questions/ * How do I test for end of file? When your BufferedReader returns null (not the empty string), you've hit the end of file. * What about blank lines? You get the empty string * How do I write "the double quote character"? "\"" /Loops/ Three kinds of loops in Java: While, For, Do while (CONDITIONAL-EXPRESSION) { BODY } STUFF-AFTERWARD "As long as CONDITIONAL-EXPRESSION is true, execute the body.": x = 5; while (x < 10) { x = x + 1; pen.println(x); } Prints 6, 7, 8, 9 Does it print 10? Yes IMPORTANT POINT: COND-EXP is only tested ONCE per execution of the body, not after every step What do for loops look like? Generally for (INIT; TEST; INCREMENT) { BODY; } EQUIV TO { INIT; while (TEST) { BODY; INCREMENT; } } Clearer when you write code for (int i = 5; i < 10; i++) { pen.println(i); } Can you have multiple initial values and increments and such? Yes, but it gets ugly Can you explain i++ * It means "add one to i, changing the value of i" What about ++i * It means "add one to i, changing the value of i" So how do they differ? * If you use them in an expression, the value of ++i is the new value of i and the value of i++ is the old value of i i = 3; x = ++i; y = i++; // x has value 4 and y has value 4 and i has value 5 What does "while (!done)" mean * done is a boolean variable. It has values true or false * ! means "not" * Intent: Keep going until I explicitly note that I'm done * Note that I'm done by assigning true to done done = true; * Terminology: done is a "loop sentinel"