CollectNewspaperKarel Solution

This lecture explains how to get started with Karel the Robot:

After watching the lecture, there are a few assignments to get you started. The first one is pretty simple and gets you to feel comfortable with the basics:

Here is my solution:

<pre>/*
 * File: CollectNewspaperKarel.java
 * --------------------------------
 * At present, the CollectNewspaperKarel subclass does nothing.
 * Your job in the assignment is to add the necessary code to
 * instruct Karel to walk to the door of its house, pick up the
 * newspaper (represented by a beeper, of course), and then return
 * to its initial position in the upper left corner of the house.
 */

import stanford.karel.*;

public class CollectNewspaperKarel extends SuperKarel {

	public void run () {
		MoveToNewspaper ();
		PickUp ();
		Return ();
	} 
	private void MoveToNewspaper () {
		move ();
		move ();
		turnRight ();
		move ();
		turnLeft ();
		move ();			
	}
	private void PickUp () {
		pickBeeper ();
		turnAround ();
	}
	private void Return () {
		for (int i = 0; i < 3; i++) {
			move();
		}
		turnRight ();
		move ();
		turnRight ();
	}
}</pre>

I’m sure there are a few solutions to this, but, most importantly, this solves the problem when it runs! I was extremely proud of accomplishing my first little program ๐Ÿ™‚

But I’m open to tips. Let me know if you see something that I can improve and apply to the next assignments.

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

  • spencer.kevin

    Hi Natasha, would you mind explaining, in your ‘for’ statement,
    the “&lt” symbol. What does it do, or mean? I must have missed that piece.

    Thanks!

    • Hi Spencer,

      the “&lt” symbol simply “<" It isn't copied over properly when the code is put into WordPress… Hopefully that makes more sense ๐Ÿ™‚

  • Pingback: Stanford CS106a Assignment 1 « Programming Zero to Hero()

  • This program would work perfectly for only this case.. Suppose I extend the size of the box that karel is in. Then again you would have to write another code to collect for that..This was your first program so it would seem reasonable u did it. But when u move further i would suggest u to write a general code that can handle similar cases easily widout the need of modification… ๐Ÿ™‚