UCL Logo

1007 Programming Principles 2005

Programming Notes and Exercises 3

Recommended finishing date: Friday 4th November 2005

Purpose: Writing programs that using keyboard input, arrays and more complex algorithms.

Goal: Complete as many of the exercise questions as you can. If you are keeping up, you need to do at least the core questions. The additional questions are more challenging and are designed to stretch the more confident programmers. Don't worry if you can't do them now, but be prepared to come back and try them later on.

Feedback: It is important that you get feedback on your exercise answers so that you know they are correct, that you are not making common mistakes, that the program code is properly presented and that you are confident you have solved the problem properly. To do this, get your answers reviewed by a lab demonstrator during lab sessions, and take printed copies of your answers (whether complete or not) along to tutorials with your academic tutor. Your tutor will expect to see your work and for you to talk about it.

NOTE: You must keep all exercise answers as they form a record of your progress. After the exams you may be required to hand-in all exercises and coursework answers, as part of the course assessment process.


Programming Notes

A number of these exercise questions require input to be read from the keyboard. Input in general is complicated, so to provide straightforward input class KeyboardInput is provided and described in the following notes. The class provides input objects that can read data of various types typed in at the keyboard.

The KeyboardInput class

These notes show how to use a class called KeyboardInput for reading values typed in at the keyboard. The class brings together a collection of useful input methods that you can call from your programs. The class is based on the one in the text book, where it is used in some of the examples and is listed in Appendix F.

Using the class you can write interactive programs that are able to input values of the following types:

  • int
  • long
  • double
  • float
  • char
  • String

The user of your interactive program has to type a value using the correct format for that type. For example, 123 would be a valid int value but xyz would not be. Reading input is always tricky as you have to deal with all the strange things that someone may type in!

If something is typed in that cannot be recognised as a value of the type being asked for, a default value is returned, rather than an error being reported. For numbers the default is zero, for char a space and for String an empty string.

Using KeyboardInput

To use the KeyboardInput class save the source code, which is listed below, into a file called KeyboardInput.java (you can use copy and paste from the web page version of these notes). Note the way the KeyboardInput is spelt using a capital K and I. You must use the same combination of upper and lower case letters.

Next compile the code to produce the file KeyboardInput.class. This file, or a copy of it, should then be placed in any directory you are using when working on your exercises. (If you want to be more sophisticated and avoid making copies of the .class file investigate how to use the CLASSPATH environment variable, or how to use a programming environment such as Eclipse.)

Note — an interactive program using KeyboardInput must be run from the command line (an xterm window, or a MS Windows Command Prompt window, or a Mac OS X terminal window).  Simply open the appropriate window, change to the correct directory and use the java command (e.g., java MyInteractiveProgram). You can still edit and compile the program using JEdit or BlueJ.

A program that needs to do input first has to create a KeyboardInput object using the KeyboardInput class. Do this by having a line in your program that looks like this:

KeyboardInput in = new KeyboardInput() ;

This line must appear before you do any input and will give you a variable called in that references a KeyboardInput object. Once you have an object you call its input methods. For example, to input an integer you would use:

int x = in.readInteger() ; 

When this statement is executed, the program will wait for you to type in some input. The input must be ended by pressing the <return> key, otherwise nothing more will happen! Once the input has been read an attempt will be made to recognise the characters that were typed in as an integer of type int. If successful the int value will be returned. If not, then a default value of 0 is returned. The variable x will be initialised accordingly.

To let someone using your program know that input is expected, it is a good idea to print a message asking for the input. For example:

System.out.print("Type a floating point number: ") ;
double d = in.readDouble() ;

Note the use of print, rather than println, so that the input follows the request on the same line.

The following test program shows the use of all the input methods provided by the class. To run this program, save the source code to a file called KeyboardInputTest.java and compile and run it, having first made sure that a copy of KeyboardInput.class is in the same directory.

class KeyboardInputTest
{
  public void runTest()
  {
    KeyboardInput in = new KeyboardInput();
    System.out.print("Type an integer: ");
    int n = in.readInteger();
    System.out.println("Integer was: " + n);
    System.out.print("Type a long: ");
    long l = in.readLong();
    System.out.println("Long was: " + l);
    System.out.print("Type a double: ");
    double d = in.readDouble();
    System.out.println("Double was: " + d);
    System.out.print("Type a float: ");
    float f = in.readFloat();
    System.out.println("float was: " + f);
    System.out.print("Type a char: ");
    char c = in.readCharacter();
    System.out.println("char was: " + c);
    // Note that reading one character leaves the newline
    // character still in the input buffer. Do an extra
    // read to use it up.
    c = in.readCharacter();
    // Newlines are represented using two characters on Microsoft
    // Windows systems, so an further read is needed.
    // c = in.readCharacter() ;
    System.out.print("Type a String: ");
    String s = in.readString();
    System.out.println("String was: " + s);
  }
  public static void main(String[] args)
  {
    KeyboardInputTest inputTest = new KeyboardInputTest();
    inputTest.runTest();
  }
}

Input Buffering

Input from the keyboard is buffered in an input buffer managed by the operating system. This means that all the characters typed are collected up and temporarily stored until the <return> key is pressed. The operating system keeps your program waiting while you are typing, so your program is not actually doing anything. Only after the <return> key is pressed does your program carry on executing. While your program is waiting we say it is suspended or blocked.

As a result of the buffering your program receives a whole line of characters at a time, not single characters one after another. The line of characters includes a newline character at the end — newline is the character generated by pressing <return>. When you read any type of value, except for char, the newline character is automatically removed and you don't see it. However, when you read a character the newline is left in place and you need to do an extra readCharacter to get rid of it. You can see this being done in the test program above, so don't forget to take this into account when reading characters. If you are using a Microsoft Windows system you will find that newlines are represented by two characters, so an extra read is needed to remove all the characters compared to a Unix system.

Note that due to buffering, calling readCharacter may simply return the next character in the buffer if one is available because the user has typed in several characters (even if only asked for one). In this case, there is no need for the program to wait for anything more to be typed in. If programs using readCharacter appear not to wait for input, then check for this situation as well as taking the newline characters into account.

The KeyboardInput class code listing follows. The class uses a number of Java features that are not covered in COMP1007 (but will be in COMP1008), along with several library classes. At this stage a detailed understanding of how the class works is not needed but it is well worth the challenge of looking through it and trying to work out what all the code does. Use the text book and online Javadoc documentation to help. Also, note the way the class has been commented. It has actually been fully commented using documentation comments, which can be automatically processed to produce online documentation in the form of web pages.

import java.io.*;
/**
 *  A simple input class to read values typed at the command line. If an error
 *  occurs during input, any exceptions thrown are caught and a default value
 *  returned.
 * 
 * @author     Graham Roberts
 * @author     Russel Winder
 * @version    1.2 Oct 2002
 */
public class KeyboardInput
{
  /**
   *  The buffered stream that connects to the keyboard so that we can read 
   *  from it sensibly.
   */
  private final BufferedReader in =
    new BufferedReader(new InputStreamReader(System.in));
  /**
   *  Read an <CODE>int</CODE> value from keyboard input.
   *
   * @return    The integer value read in, or zero if the input was invalid.
   */
  public final synchronized int readInteger()
  {
    String input = "";
    int value = 0;
    try
    {
      input = in.readLine();
    }
    catch (IOException e)
    {}
    if (input != null)
    {
      try
      {
        value = Integer.parseInt(input);
      }
      catch (NumberFormatException e)
      {}
    }
    return value;
  }
  /**
   *  Read a <CODE>long</CODE> value from keyboard input.
   *
   * @return    The long value read in, or 0L if the input was invalid.
   */
  public final synchronized long readLong()
  {
    String input = "";
    long value = 0L;
    try
    {
      input = in.readLine();
    }
    catch (IOException e)
    {}
    if (input != null)
    {
      try
      {
        value = Long.parseLong(input);
      }
      catch (NumberFormatException e)
      {}
    }
    return value;
  }
  /**
   *  Read a <CODE>double</CODE> value from keyboard input.
   *
   * @return    The double value read in, or 0.0 if the input was invalid.
   */
  public final synchronized double readDouble()
  {
    String input = "";
    double value = 0.0D;
    try
    {
      input = in.readLine();
    }
    catch (IOException e)
    {}
    if (input != null)
    {
      try
      {
        value = Double.parseDouble(input);
      }
      catch (NumberFormatException e)
      {}
    }
    return value;
  }
  /**
   *  Read a <CODE>float</CODE> value from keyboard input.
   *
   * @return    The float value read in, or 0.0F if the input was invalid.
   */
  public final synchronized float readFloat()
  {
    String input = "";
    float value = 0.0F;
    try
    {
      input = in.readLine();
    }
    catch (IOException e)
    {}
    if (input != null)
    {
      try
      {
        value = Float.parseFloat(input);
      }
      catch (NumberFormatException e)
      {}
    }
    return value;
  }
  /**
   *  Read a <CODE>char</CODE> value from keyboard input.
   *
   * @return    The char value read in, or ' ' (space) if the input was invalid.
   */
  public final synchronized char readCharacter()
  {
    char c = ' ';
    try
    {
      c = (char) in.read();
    }
    catch (IOException e)
    {}
    return c;
  }
  /**
   *  Read an <CODE>String</CODE> value from keyboard input.
   *
   * @return    The String value read in.
   */
  public final synchronized String readString()
  {
    String s = "";
    try
    {
      s = in.readLine();
    }
    catch (IOException e)
    {}
    if (s == null)
    {
      s = "";
    }
    return s;
  }
}

Arrays

The syntax for declaring, creating and using arrays is covered in both the lecture slides and the text book. In summary, an array is created as follows:

int[] myArray = new int[10]; // An array of 10 ints

An array variable (myArray in the example above), must be explicitly initialised to reference a new array object, created with a new expression. A common mistake is to forget to create the array, so always check for this if a program does not compile or work.

Array indexing, the operation used to access array elements, is done using the square bracket notation:

myArray[x] = 10;

Don't forget that an array of size 10 is indexed from 0 to 9 — indexing counts from zero. This is easy to get wrong, typically when accessing an array with a loop. A check is made at runtime that the array index given is within the array, so accessing myArray[10] will cause an array bounds error and your program will be terminated. Such errors are common, so check your array indexing and use of loops carefully.

An array knows its own size, so the expression:

myArray.length;

will return the number of elements in the array.

Enhanced For Loop

Java 5 has an enhanced for loop for iterating through collections such as arrays:

for (int n : anArray)
{
  System.out.println(n)
}

This can be read as "for each value n in anArray do ...". The variable n is initialised to each value stored in the array in turn and be used inside the loop body. Notice that no counter is needed to index into the array and the loop will work unchanged whatever the size of the array is.

Comparing Strings

Integers and integer variables can be compared using the == operator, for example x == 2. The same operator can be used to compare values of other primitive types. However, strings are objects and trying to compare strings using == won't work in the way expected. In fact, == will compare two string objects to see if they are the same object, not if they represent the same sequence of characters. Due to the complex way in which strings objects are managed this may or may not get you the result you need!

To compare strings properly you need to use the equals and compareTo methods.

The equals method will return true if two strings are identical (that is they contain exactly the same characters in the same order).

String s1 = ...
String s2 = ...
boolean b = s1.equals(s2);

b is initialised to true if the strings are the same, false otherwise.

You can also use the method equalsIgnoreCase, which will ignore the difference in case between letters, so that A is considered the same as a.

The compareTo method provides the equivalent of ==, < and >.

String s1 = ...
String s2 = ...
int n = s1.compareTo(s2);
      

compareTo will return a value less than zero if s1 comes before s2 alphabetically (for example "hello" comes before "world" in dictionary order).
compareTo will return a value of zero if s1 is the same as s2.
compareTo will return a value greater than zero if s1 comes after s2 alphabetically.

Strings are compared by looking at each character and using the ordering defined for characters. Does A come before or after a, does 1 come before or after a? The answer is in the text book, or try writing some experimental programs to work out the ordering!

More information about comparing strings can be found in the online Javadoc documentation under class String.

Accessing characters in a String

A string object actually holds an array of characters. Each character can be access using the charAt method:

String s1 = "hello";

char c = s1.charAt(1); // Get the character 'e'

This is like array indexing, except that the square bracket notation is not used. Indexing still starts from 0.

Random Numbers

Random numbers can be generated by an object of class Random (look it up in the online Java documentation). The following program illustrates the use of a Random object.

import java.util.Random; // Don't forget to include this line

class MyRandom 
{ 
  public void displayRandom()
  {
    Random generator = new Random(); 
    // Display 10 random integers 
    for (int i = 0 ; i < 10 ; ++i) 
    { 
      System.out.println(generator.nextInt()); 
    }
  }

  public static void main(String[] args) 
  { 
    MyRandom random = new MyRandom();
    random.displayRandom();
  } 
} 

Random integers can be any int value (run the program above and see what it displays).

The line starting with the keyword import tells the Java compiler that class Random is needed by the following program and must be present. A similar line is needed to use the ArrayList class but not for class String.

You might also notice that random numbers are not really random but pseudorandom! This is because the random number sequence is calculated using an mathematical formula, which given the same input values will always calculate the same sequence of numbers. Hence, you may notice the same sequences re-occurring. You can force a particular sequence by using a seed value:

    MyRandom random = new MyRandom(1234);  // Supply a seed

The seed value is added to the new MyRandom expression and can be any integer.

An alternative way of getting random numbers is to use the utility method Math.random() provided by class Math. See the on-line documentation for more information.

Class Math also provides a range of other utility methods implementing common mathematical functions.

Colour

Drawing programs can make use of colour! When using a graphics object the method setColor is used to set the drawing colour (note the spelling of colour in setColor — this is correct). The following code will draw a red rectangle:

g.setColor(Color.red);
g.drawRect(150,150,50,50);

Colours are represented by Color objects (see the documentation for class Color). SetColor requires a Color to be given as an argument . The default Colors are:

 Color.black  Color.magenta
 Color.blue  Color.orange
 Color.cyan  Color.pink
 Color.darkGray  Color.red
 Color.gray  Color.white
 Color.green  Color.yellow
 Color.lightGray  

Colours can also be specified using Red, Green and Blue (RGB) values, allowing you to pick any colour you want to work with. For example, to create your own colour you would use:

Color myColor = new Color(10,100,200); // Sort of greenish/blue
g.setColor(myColor); // Use the color

The three argument values are integers in the range 0-255, representing the mix of red, blue and green values.


Example Questions and Answers

The following are examples of questions and answers, to show how the Java syntax works, and to illustrate the kinds of programs you should be writing. There are further detailed examples in the text book.

Example3.1 Write a program to ask for, and input using the class KeyboardInput (see the separate notes) your name and a greetings message. Then display both on the screen.

Hint: You need to read in a String values and store then in variables of type String.

Answer:

// Written by A.Person, October 2005
// Answer to Ex3 example question 1
class Example3_1 
{ 
  public void inputAndDisplay()
  {
    KeyboardInput in = new KeyboardInput(); 
    System.out.print("Type your name: "); 
    String name = in.readString(); 
    System.out.print("Type in a message: "); 
    String message = in.readString(); 
    System.out.println("\n\nHello, you are: " + name); 
    System.out.println("And your message is: " + message); 
  }

  public static void main(String[] args) 
  { 
    Example3_1 example = new Example3_1();
    example.inputAndDisplay();
  } 
} 

Example3.2 Write a program to read in 10 integers and store them in an array. Then print out the contents of the array.
Answer:

// Written by A.Person, October 2005
// Answer to Ex3 example question 2
class Example3_2
{
  public void inputAndDisplay()
  {
     KeyboardInput in = new KeyboardInput();
     int[] numbers = new int[10];
     for (int n = 0 ; n < 10 ; n++)
     {
       int val = 0;
       System.out.print("Enter integer " + n +": ");
       val = in.readInteger();
       numbers[n] = val;
     }
     for (int n : numbers)
     {
       System.out.println(n);
     }
   }
  public static void main(String[] args) 
  {
    Example3_2 example = new Example3_2();
    example.inputAndDisplay();
  } 
}

Note that an enhanced for loop is used to print out the contents of the array but a standard for loop is needed when reading in the values. The second loop could be written as:

    for (int n = 0 ; n < 10 ; n++)
{
System.out.println("array[" + n + "] = " + nums[n]);
}

This allows the array to be printed showing the contents at each index position. A counter is now needed, so a stanard for loop is used.

Make sure that you get array indexing correct. If an attempt is made to access an array element that doesn't exist you will get an error message like this when the program is run:

java.lang.ArrayIndexOutOfBoundsException
	at Example3_2.inputAndDisplay(Example3_2.java:14)
	at Example3_2.main(Example3_2.java:25)
Exception in thread "main" 
Process Example3_2 exited abnormally with code 1

Hence, if you see ArrayIndexOutOfBoundsException you need to re-check all your loops and array indexing operations.

Example3.3 Write a program to input 10 words, stored as strings in an array, and then display the words in sorted order.

The goal here is to find out how to sort strings. One way is to write your own sort algorithm implementation, one of the simplest of which is Bubble Sort. This works by repeatedly working, or iterating, through the array comparing each pair of strings and swapping the pair if they are in the wrong order. Each time the array is iterated through it becomes more sorted as elements move to their correct position. If done enough times the array will be fully sorted (try some examples by hand if you are unsure how this works). How many times are enough? The worst case is moving an element from one end of the array to the other, doing n-1 swaps (assuming the array is of size n). Hence, going through the array n-1 times will guarantee it will be sorted. In practice, the array is likely to be sorted in less than n-1 iterations, and sorting can be stopped if no swaps are done in a single interation.

This program illustrates the algorithm, using the compareTo method to compare strings:

// Written by A.Person, October 2005
// Answer to Ex3 example question 3
class Example3_3
{
  public void sort()
  {
    KeyboardInput in = new KeyboardInput();
    String[] words = new String[10];
    for (int n = 0 ; n < words.length ; n++)
    {
      System.out.print("Enter word " + n + ": ");
      words[n] = in.readString();
    }
    
    // Sort using bubble sort
    for (int i = 0 ; i < words.length-1 ; i++)
    {
      for (int j = 0 ; j < words.length-1 ; j++)
      {
        if (words[j].compareTo(words[j+1]) > 0)
        {
          String tmp = words[j];
          words[j] = words[j+1];
          words[j+1] = tmp;
        }
      }
    }
    System.out.println("Sorted words:");
    for (String s : words)
    {
      System.out.println(s);
    }
  }

  public static void main(String[] args)
  {
    Example3_3 example = new Example3_3();
    example.sort();
  }
}
      

Note the use of words.length in the for loops. This avoids having to use the number 9. If the size of the array is changed, the loops will not need to be edited as they get the array length from the array rather than using a fixed number.

A slight improvement to the program above would be to stop sorting if no swaps are done during one iteration through the array (as the array is already sorted):

// Written by A.Person, October 2005
// Answer to Ex3 example question 3
class Example3_3b
{
  public void sort()
  {
    KeyboardInput in = new KeyboardInput();
    String[] words = new String[10];
    for (int n = 0 ; n < words.length ; n++)
    {
      System.out.print("Enter word " + n + ": ");
      words[n] = in.readString();
    }
    
    // Sort using bubble sort
    boolean swapped = false;
    for (int i = 0 ; i < words.length-1 ; i++)
    {
      for (int j = 0 ; j < words.length-1 ; j++)
      {
        if (words[j].compareTo(words[j+1]) > 0)
        {
          String tmp = words[j];
          words[j] = words[j+1];
          words[j+1] = tmp;
          swapped = true;
        }
      }
      if (!swapped)
      {
        break; // no swaps, so array sorted
      }
    }
    System.out.println("Sorted words:");
    for (String s : words)
    {
      System.out.println(s);
    }
  }

  public static void main(String[] args)
  {
    Example3_3b example = new Example3_3b();
    example.sort();
  }
}
      

Bubble sort is not very fast or efficient, although you won't notice when sorting only 10 items, and does too many unnecessary comparisons. Much effort has been put into developing efficient sort algorithms, so it makes sense to use those that have already been developed and tested. Searching through the Java class library reveals a class Arrays that provides various sort methods, including one that will sort an array of strings. Using the library method gives the following program:

// Written by A.Person, October 2002
// Answer to Ex3 example question 3
import java.util.*;

class Example3_3c
{
  public void sort()
  {
    KeyboardInput in = new KeyboardInput();
    String[] words = new String[10];
    for (int n = 0 ; n < words.length ; n++)
    {
      System.out.print("Enter word " + n + ": ");
      words[n] = in.readString();
    }
    
    // Sort using library method
    Arrays.sort(words);
    
    System.out.println("Sorted words:");
    for (String s : words)
    {
      System.out.println(s);
    }
  }

  public static void main(String[] args)
  {
    Example3_3c example = new Example3_3c();
    example.sort();
  }
}
      

Note that this program starts with the line import java.util.Arrays ;. This is needed to tell the compiler where to locate the class Arrays that provides the sort method.


Example 3.4 Write a drawing program to display a pattern of blue and yellow crosses, like this:

Grid Pattern

Hint: Find the pattern by which the colours alternate row by row.
An array of colours forming the pattern might be helpful...

The key to drawing this pattern is to note that the colours of the squares cycle through a pattern of length 10 both horizontally and vertically. An array of colours can be used to store the pattern, and then the array can be cycled through to draw a row of squares. The next row is drawn by starting the cycle from a different position using a simple formula as the offset is regular. This leads to a simple piece of code:

public void doDrawing(Graphics g)
    {
      int squareSize = 15;
      int width = 20;
      int height = 20;
      Color[] colourCycle = new Color[]{Color.yellow,Color.blue,Color.blue,
                                  Color.blue,Color.yellow,Color.blue,
                                  Color.yellow,Color.yellow,Color.yellow,
                                  Color.blue};
      int cycleLength = colourCycle.length;                                                           
      int line = 1;
      for (int row = 0 ; row < width ; row++)
      {	  
        int colour = line;   
        line = (line + 3) % cycleLength; 
        for (int col = 0 ; col < height ; col++)
      	{
          g.setColor(colourCycle[colour++ % cycleLength]);
          g.fillRect(col*squareSize, row*squareSize, squareSize, squareSize);
        }
      }
    }

Don't forget this method should be placed within the drawing program template to create a complete program.

The program above represents one solution to the problem but certainly not the only one. Can you find a better alternative? And what does 'better' actually mean with respect to a program?


Core questions

Q3.1 Write an interactive program using the KeyboardInput class that inputs your name (a String) and an integer, and then displays your name the number of times specified by the integer.


Q3.2 Write a program that inputs a sequence of Strings until the word stop is entered.

Hint: You compare strings using compareTo, as outlined in the preceding notes.


Q3.3 Write an interactive program that uses a loop to input a sequence of single characters until the character # is entered. Remember that type char is used to store characters. Characters can be compared using the == operator.

Note — this is not quite as straightforward as it may seem, as entering a single character also results in a newline character being input when the <return> key is pressed. Hence, extra reads are needed to remove the newline character(s). See the KeyboardInputTest program listed in the notes above.

What happens if you input a word instead of a single character?

As Windows uses two characters to mark the end of a line (newline and carriage return), you will find that your program may work properly under Windows and not Unix or vice versa. Can you write a version of the program that works correctly under both Windows and Unix?


Q3.4 Write a program that inputs three strings (words or sentences) and determines which string comes alphabetically last.

Hint: compareTo will tell you the ordering.


Q3.5 Write a program to input 10 doubles (values of type double) and store them in an array. Then compute and display the average of the values input. Try entering negative as well as positive numbers. Consider writing one method to do the input and another to compute the average.


Q3.6 Repeat Q3.5, except that the user should first be asked how many doubles will be entered, rather than the number being fixed at 10.

Hint:: Create an array of the correct size after the user has entered the number of doubles to be input.


Q3.7 Write a program to input 10 words, storing them as strings in an ArrayList (not an array), and then display the words in reverse sorted order.


Q3.8 Write a program to read a line of text and then display each word in the text on a separate line.

Hint: Read the earlier notes on accessing characters in a string. You'll also need to define what makes a word as far as your program is concerned.


Q3.9 Write a program to generate 10000 random doubles between -0.9999999 and +0.9999999. Print out the largest, smallest and the average values.

Do you need an array? Think very carefully about this.

Hint: Look at the documentation for class Random and find the method nextDouble.
Another hint: Negative values?? class Random also has nextBoolean...


Q3.10 Write a drawing program to display a pattern of blue and red triangles like this:

Triangle Pattern

Hint: look at the fillPolygon method in class Graphics.


Q3.11 Write a drawing program to generate and draw a maze like this one:

Maxe


Harder Questions

Q3.12 Write a Robot program that will get the robot to pick up a sequence of widgets and place them in the room to form a shape, such as a square or circle.

Hints: Don't do this by writing a long list of statements to individually position each widget. Instead consider storing the widget pattern into a 2D array (effectively storing the (x,y) locations), and then writing a method to move the robot to the correct position to place a widget. By iterating through the 2D array, the method can be called to place a widget where indicated by the 2D array contents. To position the robot you will need to move relative to a reference location such as the top left corner (0,0), the robot still has no memory of its position.


3.13 Write a program to display the current date and time.

Hint: find out about Calendar classes, in particular GregorianCalendar.


Challenges

3.14 Write a Robot program to move the robot to the door of any size room that can contain any combination of obstacles. To do this you will need an algorithm with some kind of memory, so that the robot does not repeat a path it has already followed and get stuck inside a cycle.


3.15 Modify the drawing program so that you can draw lines and rectangles interactively on the screen using the mouse.

Hint: This is quite a big challenge. You will need to find out about Swing user interface components and event handling. See the Swing tutorial at: http://java.sun.com/docs/books/tutorial/uiswing/

Last updated: September 1, 2006

Computer Science Department - University College London - Gower Street - London - WC1E 6BT - Telephone: +44 (0)20 7679 7214 - Copyright 1999-2006 UCL


 Search by Google