CS 145 Lecture 19 – While
Dear students,
Let’s start by analyzing this piece of code:
public static boolean isIsosceles(double sideA, double sideB, double sideC) { if (sideA == sideB) { if (sideB == sideC) { return true; } else { return false; } } else { return false; } }
Sniff it. Kick it. Pounce on it. Does it hold up?
We talk about splitting up the flow of a program across branches with if
statements. Even with branching, our program steadily advances, always getting closer to the end of our program. Sometimes, however, we’d like to go back to code that we’ve executed before. This is called a loop.
Loops come in several forms in Java, and today, we will focus on one. I am ashamed at the number of resources for learning that start by enumerating every possible tool available to you. That is useful information delivered at the wrong time. Let’s meet while
:
// pre loop work while (booleanCondition) { // work to repeat // update terms of boolean condition } // post loop work
We’ll write a few while
loops to accomplish the following tasks:
- Write a countdown application.
- Write a flashcard app for practicing with the mod operator.
- Write an app that prompts you to complete an acrostic.
- Write an app that hijacks the mouse and spins it in a circle.
See you next class!
Sincerely,
Isoceles.java
package lecture1024; public class Isoceles { public static void main(String[] args) { // System.out.println(0.30000000000000004000); System.out.println(isIsosceles(0.1 + 0.2, 0.2, 0.300000000000000)); } public static boolean isIsosceles(double sideA, double sideB, double sideC) { System.out.printf("%.20f %.20f %.20f", sideA, sideB, sideC); //return sideA == sideB || sideB == sideC || sideA == sideC; return Math.abs(sideA - sideB) < 1.0e-3 || Math.abs(sideB - sideC) < 1.0e-3 || Math.abs(sideA - sideC) < 1.0e-3; } }
Countdown.java
package lecture1024; public class Countdown { public static void main(String[] args) throws InterruptedException { int timer = 10; while (timer >= 0) { System.out.println(timer); --timer; Thread.sleep(1000); } } }
Acrostic.java
package lecture1024; import java.util.Scanner; public class Acrostic { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("One-word theme, per favore? "); String theme = in.nextLine(); theme = theme.toUpperCase(); int i = 0; while (i < theme.length()) { System.out.print(theme.charAt(i)); in.nextLine(); i++; } } }