# Karel Defends Democracy Assignment And Solution

So if you were able to complete all the Assignment 1 problems, this one shouldn’t really take you that long. Here is the assignment:

This assignment is presented during the student Section, so there is no zip file for it to download. However, it is not that difficult to set this up yourself. To get started, click the green “C” button and create a class called “defendDemocracyKarel”. Now you can start a file with the following commands:

You also need to create a new world, as is shown in the assignment. Simply load Karel, and it’s pretty simple to create new worlds.

Here is my solution (although the solution is also available on the assignment site)

This time, I was very conscious of decomposition and making sure I solve the problem top-down. I also included comments of my thinking.

```&lt;pre&gt;/* Karel is cleaning up the voting ballot.
* The vote only counts if the middle rectangle is punched,
* which means there are no beepers present.
*/

import stanford.karel.SuperKarel;

public class defendDemocracyKarel extends SuperKarel {

public void run() {
while (frontIsClear()) {
move();
checkMiddleBeeper();
cleanExtraBeepers();
move();
}
}
private void checkMiddleBeeper() {
if (beepersPresent()) {
move();
move();
}
}
private void cleanExtraBeepers() {
if (noBeepersPresent()) {
cleanBeepersNorth();
}
}
/* Karel moves South, checks for beepers, and picks them up
* if there are any there.
* Pre-condition: Karel is in the middle of a rectangle with no
* middle beeper
* Post-condition: Karel returns to middle facing North
*/
turnRight();
move();
while (beepersPresent()) {
pickBeeper();
}
turnAround();
move();
}
/* Karel moves North, checks for beepers, and picks them up
* if there are any there.
* Pre-condition: Karel is in the middle of a rectangle with no
* middle beeper
* Post-condition: Karel returns to middle facing East
*/
private void cleanBeepersNorth() {
move();
if (frontIsClear()) {
move();
}
while (beepersPresent()) {
pickBeeper();
}
turnAround();
move();
turnLeft();
}
}&lt;/pre&gt;

```

Ok, saying goodbye to Karel and growing into Java!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.