Previous Next |
Workshop: Teaching Your Computer a LessonThis hour's workshop provides evidence that you cannot punish your computer in the same way that Bart Simpson is punished at the beginning of each episode of The Simpsons. Pretend you're a teacher and the computer is a kid who contaminated your morning cup of coffee with Thorium 230. Even if you're the most strident liberal, you realize that the computer must be taught a lesson—it's not acceptable behavior to give the teacher radiation poisoning. Your computer must be punished, and the punishment is to display the same sentence over and over again. The Repeat program will use a loop statement to handle a System.out.println() statement again and again. Once the computer has been dealt this punishment for 1,000,000 sentences or one minute, whichever comes first, it can stop running and think about the error of its ways.
Use your word processor to create a new file called Repeat.java. Enter the text of Listing 8.2 and save the file when you're done. Listing 8.2. The Full Source Code of Repeat.java1: import java.util.*; 2: 3: class Repeat { 4: public static void main(String[] arguments) { 5: String sentence = "Thorium 230 is not a toy."; 6: int count = 10; 7: Calendar start = Calendar.getInstance(); 8: int startMinute = start.get(Calendar.MINUTE); 9: int startSecond = start.get(Calendar.SECOND); 10: start.roll(Calendar.MINUTE, true); 11: int nextMinute = start.get(Calendar.MINUTE); 12: int nextSecond = start.get(Calendar.SECOND); 13: while (count < 1000000) { 14: System.out.println(sentence); 15: GregorianCalendar now = new GregorianCalendar(); 16: if (now.get(Calendar.MINUTE) >= nextMinute) { 17: if (now.get(Calendar.SECOND) >= nextSecond) { 18: break; 19: } 20: } 21: count++; 22: } 23: System.out.println("\nI wrote the sentence " + count 24: + " times."); 25: System.out.println("I have learned my lesson."); 26: } 27: } The following things are taking place in this program:
Compile the program with the javac compiler tool or another compiler and then give it a try. Using the JDK, you can run it by typing the following at the command line: java Repeat Run this program several times to see how many sentences are displayed in a minute's time. The Repeat program is an excellent way to see whether your computer is faster than mine. During the testing of this workshop program, Repeat usually displayed around 530,000 sentences in a minute's time. If your computer displays the sentence more times than mine does, don't just send me your condolences. Buy more of my tutorials so I can upgrade. |
Previous Next |