cs106a练习题第一部分第三题,一个karel的奇怪的现象
小弟是初学者,谢谢了In this exercise, your job is to get Karel to create a checkerboard pattern of beepers inside
an empty rectangular world, as illustrated in the following before-and-after diagram.
(Karel’s final location and the final direction it is facing at end of the run do not matter.)
This problem has a nice decomposition structure along with some interesting algorithmic
issues. As you think about how you will solve the problem, you should make sure that
your solution works with checkerboards that are different in size from the standard 8x8
checkerboard shown in the example. Odd-sized checkerboards are tricky, and you should
make sure that your program generates the following pattern in a 5x3 world:
Another special case you need to consider is that of a world which is only one column
wide or one row high. The starter folder contains several sample worlds that test these
special cases, and you should make sure that your program works for each of them.
我编的程序:
import stanford.karel.*;
public class CheckerboardKarel extends SuperKarel {
public void run(){
putLineBeeper();
while (notFacingNorth()){
if (beepersPresent()){
turnNextLine();
putLineBeeper_1();
}
else {
turnNextLine();
putLineBeeper();
}
}
}
private void putLineBeeper() { //隔一格放一个,放一行beepers,第一格放
while (frontIsClear()){
putBeeper();
move();
if (frontIsClear()){
move();
}
}
turnAround(); //纠正“少一”错误
move();
if (beepersPresent()){
turnAround();
move();
}else {
turnAround();
move();
putBeeper();
}
}
private void putLineBeeper_1() { //隔一格放一个,放一行beepers,第一格不放
while (frontIsClear()){
move();
putBeeper();
if (frontIsClear()){
move();
}
}
}
private void turnNextLine() { //换行
if (facingEast()){
turnNorth();
if (frontIsClear()){
move();
turnWest();
}
}
else {
if (facingWest()){
turnNorth();
if (frontIsClear()){
move();
turnEast();
}
}
}
}
//由于转左转右命令都是相对方向,容易混乱,所以一下定义转东南西北函数
private void turnNorth(){
while (notFacingNorth()){
turnLeft();
}
}
private void turnEast(){
while (notFacingEast()){
turnLeft();
}
}
/* private void turnSouth(){
while (notFacingSouth()){
turnLeft();
}
} */
private void turnWest(){
while (notFacingWest()){
turnLeft();
}
}
}
运行倒是正确,在8X8和5X3都能得到正确的结果
可是在8X8运行时,在karel走到左上角(1,8)并转向北边后,会转身(turnAround)然后走下一个格(1,7),然后再转身回去,程序才结束
很是困惑,检查程序N多遍,都没找到karel为什么会做这个动作
特来求教
谢谢
----------------解决方案--------------------------------------------------------