Problem 2

The basics of problem 2 is “Karel has been hired to repair the damage done to the Quad in the 1989 earthquake. In particular, Karel is to repair a set of arches where some of the stones (represented by beepers, of course) are missing from the columns supporting the arches”, which means that you have to replace empty places with a beeper!. The rules are:

Karel may count on the following facts about the world:

  • Karel starts at 1st Avenue and 1st Street, facing east, with an infinite number of beepers.
  • The columns are exactly four units apart, on 1st, 5th, 9th Avenue, and so forth.
  • The end of the columns is marked by a wall immediately after the final column. This wall section appears after 13th Avenue in the example, but your program should work for any number of columns.
  • The top of the column is marked by a wall, but Karel cannot assume that columns are always five units high, or even that all columns are the same height.
  • Some of the corners in the column may already contain beepers representing stones that are still in place. Your program should not put a second beeper on these corners.

Remember to change the run configurations as from the previous post on how to setup the environment to the StoneMasonKarel for the main class, here is the my java file for this problem 2.

My way of fixing the stones is to go up the supporting line and replace the stones (beepers) and then come back down again and move along 4 positions if able to, and repeat, since in the rules you the height of the building can change which is why I come back down again from the top of the buildings.

/*
 * File: StoneMasonKarel.java
 * --------------------------
 * The StoneMasonKarel subclass as it appears here does nothing.
 * When you finish writing it, it should solve the "repair the quad"
 * problem from Assignment 1.  In addition to editing the program,
 * you should be sure to edit this comment so that it no longer
 * indicates that the program does nothing.
 */
 
import stanford.karel.*;
 
public class StoneMasonKarel extends SuperKarel {
 
	// move up the row and find replace any missing "stones"
	// checking to make sure that we have not reached the top
	private void replaceStones()
	{
		// check for a stone or wall! move in that direction
		while (true)
		{
			if (!beepersPresent())
				putBeeper();
			if (frontIsBlocked()) break;
			move();
		}
	}
 
	private void comeBackDown()
	{
		turnAround();
		while (!frontIsBlocked())
			move();
	}
 
	// need to go up and down move 4 and then up and down
	private void moveAlong()
	{
		while (true)
		{
			turnLeft();
			replaceStones();
			comeBackDown();
			turnLeft();
			if (!frontIsBlocked())
				for (int i =0; i < 4; i++)
					move();
			else
				break;
		}
 
	}
 
	public void run()
	{
		moveAlong();
	}
}

again the zile file attached is the whole assignment 1 problems, so you can download that for the full source code and the PDF assignment details.

Arrays

Arrays are ways of having a block of memory allocated to a single variable type, this allows for holding the national lottery numbers within an array of 6 instead of actually having 6 different variables, saves on variable overload

e.g.

int value1 = 1;
int value2 = 2;
int value3 = 3;
int value4 = 4;
int value5 = 5;
int value6 = 6;

and instead you could just have

int[] values = {1,2,3,4,5,6};

This is example code of how to use arrays.

public class arraytest
{
       public static void main(String[] args)
       {
              // the main method passes in parameters from the console command line 
              // e.g. ./arraytest hi there, hi there are two parameters
              for (int i =0; i < args.length; i++)
              {
                     System.out.println(args[i]);
              }
 
              // to create a array of numbers
              int[] intarray = {0,2,3,4};
 
              for (int i =0 ; i < intarray.length; i++)
              {
                     System.out.println(intarray[i]);
              }
       }
}

After compiled the above code and executed the class file that would be generated by

Java arraytest hi there

The output of the program would be

hi
there
0
2
3
4

But if the console command line was empty then just the number values would be outputted since they are inserted into the code and the ‘hi there’ was inserted manually on the command line.

Interfaces

An interface describes what functions an implemented class will have to code. E.g. if a class was a car and the interface had functions for how many doors etc, then a class of Vauxhall that implements the interface would have to code the function to return the correct amount of doors.

Here is the code, I usually find the code explains it better.

// defines the fuctions that have to be implemented by a implementable class
interface implementThese
{
       void printHi();       // have to implement these
       void printBye();
}
 
// the interClass will implement the interface implementThese
class interClass implements implementThese
{
       public void printHi()
       {
              System.out.println("Hi");
       }
 
       public void printBye()
       {
              System.out.println("Bye");
       }
}
 
class inter
{
       public static void main(String args[])
       {
              interClass in = new interClass();
              // call the classes functions.
              in.printHi();
              in.printBye();
       }
}

If you save as inter.java, and then run the output will be

Hi
Bye

There can be many interfaces per class to be implemented.

Generics

A Generic is a way to declassify the type of variable used, e.g. if there was a function to add up two integer values, but you had two double values, then the int function would not function correctly, so there would be a need to function overload the function to allow for the double increment as well. But just envisage that the same function would be required for characters, floats, personally created ones etc, then there would be more functions per type of variable than the actual work done.

A generic class negates this by allowing any class type passed to the function, as long as the type has the standard increment process defined, it will work with any type.

This will demonstrate the basics of the generics.

// the class for the generics (the T is the object of any type)
class genericsClass<T> 
{
       T val;              // private object val of type T
       public genericsClass(T t)       // constructor for the class
       {
              val = t;              // set the internal to the passed value
       }
 
       public T returnValue()       // return the internal value
       {
              return val;
       }
}
 
// main runable class
public class generics
{
       public static void main(String args[])
       {
              // create a Integer class with a default value of 3
              genericsClass<Integer> genInt = new genericsClass<Integer>(3);
              System.out.println("Value= " + genInt.returnValue());
 
              // create a String class with a default value of "hi there"
              genericsClass<String> genStr = new genericsClass<String>("hi there");
              System.out.println("Value = " + genStr.returnValue());
       }
}

If you save the code and run with java version 1.5 + (since this was part of java 1.5). The output will be

Value = 3
Value = hi there

As you can see the same class is able to use both integer and strings as the default variable type.

Method – Add Two numbers

This tutorial uses the same code as Add Two Numbers but includes a function/method to add two numbers together and return a value. In this case the value is a integer (int) and that is why the int is just before the name of the method (addIntegers) with two parameters passed to the method, these are the values that are being added together. I have called them a and b, so that they are different names to the variables within the main method.

The source code

// just import the BufferedReader and inputstream reader
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
class addtwonumbers_function
{
       // private = local to this class
       private static int addIntegers(int a, int b)
       {
              return (a+b);
       }
 
       public static void main(String[] args)
       {
              // system.in reader (e.g. the input from the console)
              InputStreamReader ISR = new InputStreamReader(System.in);       
              // buffer the console reader
              BufferedReader BR = new BufferedReader(ISR);                     
 
              // the default values for the two numbers
              int val1 = 0;
              int val2 = 0;
              try 
              {
                     // output the question.
                     System.out.print("Enter first number : ");
                     // read in the console intput one line (BR.readLine) and then convert to a integer
                     val1 = Integer.parseInt(BR.readLine());
                     System.out.print("Enter second number : ");
                     val2 = Integer.parseInt(BR.readLine());
              }
              catch (Exception ex)
              {
                     // if the input was a string.
                     System.out.println(ex.toString());
              }
              // output the answer of adding both of the values together
              System.out.println("Answer = " + addIntegers(val1, val2));
       }
}

save as addtwonumbers_function.java, this program will function the same as the previous tutorial apart from the inner working will call the method. The method programming allows for one method to be called multiple times, e.g. Within the example above there could be a method that was 5 lines in length and instead of writing the same 5 lines each time, you just write a method that is called.

Class structure

This is a general tutorial about the class structure of programming languages.

The class is basically an object that allows public methods (accessed outside that class object) and private methods (the internal class logic) and protected with is the same as private apart from an inherited class can access the protected objects. Basically the 3 main types

Public : Access from outside the class, and internal of course, with inherited etc.
Protected : Access from inherited of the class, but not called from the class object.
Private : Access from only the class and friends of the class.

This is 3 Java source code to demonstrate

class classexample
{
       private       int value1;
       private       int value2;
       protected int value3;
 
       public int addtwo(int a, int b)
       {
              value1 = a;
              value2 = b;
              value3 = (a + b);
              return value3;
       }
 
       public int returnValue1()
       {
              return value1;
       }
}

save as classexample.java

class classexample2 extends classexample
{
       public int returnValue2()
       {
              //return value2;       // will error due to value2 is private in the inherited class
              return 0;              // to be able to compi
       }
 
       public int returnValue3()
       {
              return value3;       // fine since a protected part of the inherited class
       }
}

save as classexample2.java

class classex
{
       static public void main(String args[])
       {
              classexample example1 = new classexample();
              classexample2 example2 = new classexample2();
              System.out.println("Class 1, adding two numbers and setting the internal numbers");
              System.out.println(example1.addtwo(3,4));
              // of course will return 0, because example2 is not connected to example1 class, 
              // it just extends the definition of that class.
              System.out.println(example2.returnValue3());
       }       
}

save as classex.java

And to compile the tutorial just need to java classex because java will compile the other classes as well (and creates the class files). Once compiled the output will be

Class 1, adding two numbers and setting the internal numbers
7
0

Local variables

This is a tutorial about variable scope, a variable is a means to store data within the context of the program. For example, if you wish to store a numerical value then you would not store that number in a string, but within a integer or floating point number.

There are different types of variables, integer / string etc, but the scope of a variable is the area in which the variable is defined within block of code that it is situated.

This is some java code to demonstrate the difference between local variables and global.

class localvariable
{
       private static int value1 = 1;
 
       static public void globalVariable()
       {
              System.out.println("Global : " + value1);
       }
 
       static public void main(String args[])
       {
              int value1 = 0;
              globalVariable();
              System.out.println("Local : " + value1);
              return;
       }
       return 0;       
}

the output would be

Global : 1
Local : 0