Handout #10 CS 106A June 24, 2009 Control Statements in Karel Thanks to Eric Roberts for basically this entire handout The Karel the Robot Learns Java book includes several examples that illustrate the use of control statements in Karel’s world. Whenever possible, I like to solve different problems in lecture so that you can see a different set of examples. Today, for example, I will present the concept of control statements in the context of teaching Karel to climb a mountain. In the text, you can read a similar introduction in the context of having Karel repair potholes in a roadway. By offering both examples, you are in a better position to understand the general principles as opposed to the details of a particular problem. In a lecture, however, I also want to be able to get you to think about the problems and solve them as we go. If I include the solution in the handout, it’s far too tempting just to look at the answer instead of trying to work things out on the fly. Thus, I use these handouts to describe the problems, and then put the solutions up on the web so that you can look over the solutions after class. Climbing a mountain The first problem I want to solve today is that of getting Karel to climb mountains. Like everything else in Karel’s world, the mountain is abstract and must be constructed from the available materials, specifically beepers and walls. In this problem, for example, it makes sense to use walls for mountains, as in the following world: 4 3 2 1 1 2 3 4 5 6 7 The goal is to get Karel to climb the mountain, put down a beeper to serve as a flag, and then to descend from the mountain, like this: 4 3 2 1 1 2 3 4 5 6 7 –2– At first, the goal is simply to solve the specific problem posed by this mountain. From there, however, it becomes important to generalize the problem so that it would be easy to teach Karel to climb a larger mountain with the same structure, like this: 5 4 3 2 1 1 2 3 4 5 6 7 8 9 I’ll go through several different versions of a mountain-climbing program, introducing the for, while, and if control statements along the way. Creating a line of beepers The second problem I will introduce toward the end of the hour is that of writing a method createBeeperLine, which creates a line of beepers beginning at Karel’s current corner and proceeding forward to the next wall. For example, if you were to execute createBeeperLine in an empty world, you would see something like the following before-and-after diagram: Before After 4 4 3 3 2 2 1 1 1 2 3 4 5 6 1 2 3 4 5 6 The problem is slightly harder than it looks. Unless you think carefully about the problem, it is easy to find yourself making a common programming error that keeps the program from working as you’d like.