CS 145 Lecture 9 – Loops: for and while
Agenda
- exam coming up!
- for loop problems
- digitizing a circle
- spreadsheet fill
-
for (INIT; TEST; UPDATE) { ACTION }
-
INIT while (TEST) { ACTION UPDATE }
- while loop problems
- summing an indefinite number of numbers
- checking for repeated words
- decomposing a comma-separated list
- prompting for an actual file
TODO
- Read chapter 3 (mostly discussed already) and section 4.1.
Testing pattern
For non-real primitives:
System.out.println(EXPECTED == ACTUAL);
System.out.println(2 == getParentCount()); // for example
For float and double:
System.out.println(Utilities.equalsEnough(EXPECTED, ACTUAL));
System.out.println(Utilities.equalsEnough(3.14159, getPi()); // for example
For objects:
System.out.println(ACTUAL.equals(EXPECTED));
System.out.println(sortedVowels.equals("aeiou")); // for example
Code
MoreFor.java
package preexam1; public class MoreFor { public static void main(String[] args) { fillDown(3, 1, 10); // makeCircle(10); } public static void fillDown(int first, int second, int n) { int diff = second - first; for (int i = 0; i < n; ++i) { System.out.println(first + diff * i); } System.out.println("------------"); for (int i = first; i < first + diff * n; i += diff) { System.out.println(i); } } public static void makeCircle(int n) { double jump = 360.0 / n; for (int i = 0; i < n; ++i) { // System.out.println(i); double theta = i * jump; double x = Math.cos(Math.toRadians(theta)); double y = Math.sin(Math.toRadians(theta)); System.out.println(x + "," + y); } } }
While.java
package preexam1; import java.util.Scanner; public class While { public static void main(String[] args) { Scanner in = new Scanner(System.in); int sum = 0; while (in.hasNextInt()) { int i = in.nextInt(); sum += i; } System.out.println(sum); String team = "Joel,John,Patrick,Brian,Phil,Michael"; Scanner teamParser = new Scanner(team); teamParser.useDelimiter(","); int i = 1; while (teamParser.hasNext()) { String member = teamParser.next(); System.out.println(i + ". " + member); i++; } } }
Haiku
Life can feel loopish.
Wake, eat, class, eat, work, eat, sleep…
You need some Random.
Wake, eat, class, eat, work, eat, sleep…
You need some Random.