UCL Logo

1007 Programming Principles 2005

Programming Notes and Exercises 1

Recommended finishing date: Friday 14th October 2005


Purpose: Some basic programming exercises for becoming familiar with the Java programming tools and writing some simple programs.

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.


Introduction

For these exercises you will be working with two kinds of program. The first kind are simple Java programs that have this basic structure:

class ClassName 
{ 
  public void doSomething()
  {
    // Your statements go here.
  }

  public static void main(String[] args) 
  { 
    // Create an object and tell it to do something
    ClassName name = new ClassName();
    name.doSomething();
  }
}

The lines of source code in bold represent the basic infrastructure that must be included in any program for it to be syntactically correct. For now you will have to take these for granted and simply type them in. As the course progresses, their true purpose and meaning will be explained.

Source code is typed into the computer using an editor — you should be using JEdit or BlueJ — and then saved to a file. The class name ClassName is effectively the name of the program, and the source should be saved into a file of the same name with '.java' appended. For example class ClassName should be saved in ClassName.java. When you write programs you should substitute a different class name for each program (so, don't call every one ClassName, it is just an example name!). The name should try to describe what the program does. It should also start with a capital letter and not include any spaces or punctuation marks.

All programs, however simple, should start with two lines of comments, the first stating who wrote the program and the date, the second giving a brief explanation of what the program does:

// Written by A.Person 2/10/05
// This program displays some useful information.
class ClassName 
{ 
etc.

The code you write for your program should be substituted for the comment line '// Your program statements here'. A statement is the term used to denote one complete action or command forming part of your program.

A program can be compiled using the javac command, typed in at the command line:

 javac ProgramName.java

and executed using the java command:

 java ProgramName

When the compilation is successful a .class file is created and will appear in your directory (for example, ProgramName.class). This file contains the code to execute your program so don't delete it!

When using JEdit you can also use the JEdit console to compile and run programs. Experiment with JEdit to find out how this is done. The JEdit website is at http://www.jedit.org if you want additional information.

When you use BlueJ, click the compile button in the editor window to compile the program. Then right-click on the icon in the main window and select void main(args) from the menu. The output will appear in a window. The BlueJ website is at http://www.bluej.org is you want to find out more about using it.

Drawing Pictures

The second kind of program you will be writing is for displaying simple drawings created from lines and other shapes. Like the simple program structure described above, drawing programs require some predefined infrastructure, which you will have to take as given for the time being. You need to locate the comments indicating where changes should be made and substitute your code as necessary.

The code for the simple drawing program is as follows (the fixed infrastructure code is in bold):

// Written by A.Person, 1/10/05
// This program draws a simple picture.


// Use code from the Java libraries
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


// This program will be called Drawing and needs
// to stored in a file called Drawing.java.
// To create your own program with a different name,
// change *all* the occurances of Drawing to the new
// name. Save the program to a new file named using the
// new name with .java appended.
class Drawing extends JFrame
{
  class DrawPanel extends JPanel
  { 
    //---------------------------------------------------
    // This part of the program does the actual drawing.
    public void doDrawing(Graphics g)
    {
      // You add/change the statements here to draw
      // the picture you want.
      g.drawLine(0,0,300,300);	
    }
    //---------------------------------------------------

    // This controls the drawing of the window
    // contents.
    public void paint(Graphics g)
    {
      g.setColor(Color.white);
      g.fillRect(0,0,getWidth(),getHeight());
      g.setColor(Color.black);
      doDrawing(g);
    }	

    // This part of the program makes sure that
    // the window drawing area ends up being the
    // right size. You don't need to change this.
    public Dimension getPreferredSize()
    {
      return new Dimension(WIDTH,HEIGHT);
    }
	
    // These set the size of the drawing area.
    // By default this will be 300 by 300 pixels.
    // Change the sizes to suit what you need.
    private int WIDTH = 300;
    private int HEIGHT = 300;
  }
  
  // Create a new window frame.
  public Drawing(String name)
  {
    super(name);
    setupWindow();
  } 
    
  // Tell the window object to display itself.
  public void display()
  {
    pack();
    setVisible(true);
  }
  
  private void setupWindow()
  {
    // Create the contents of the window. The top (or Center)
    // part is the drawing area. The bottom (or South) strip 
    // holds a quit button.
    DrawPanel drawing = new DrawPanel();
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new BorderLayout());
    JButton quitButton = new JButton("Quit");
    buttonPanel.add("Center",quitButton);
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add("Center",drawing);
    getContentPane().add("South",buttonPanel);
    // The event listeners are set up here to enable the
    // program to respond to events.
    quitButton.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent evt)
      {
        quit();
      }
    });
    addWindowListener(new WindowAdapter()
    {
      public void windowClosing(WindowEvent evt)
      {
        quit();
      }
    });
  }

  // This will terminate the program when the user
  // wants to quit.
  private void quit()
  {
    System.exit(0);
  }  

  // This part of the program sets everything up
  // and displays the drawing window.
  public static void main(String[] args)
  {
    // Create the window object with the label
    // "My Drawing". Change the label text to change
    // the label.
    Drawing frame = new Drawing("My Drawing");
    frame.display();
  }
}

To run this program, type in the program code and store it into a file called Drawing.java (or if you are paying attention use copy and paste from the web page version of these exercises to avoid typing in all the code!) Compile the code using the command:

javac Drawing.java

and then run the program using:

java Drawing

A window like this should appear on the screen: Drawing Window

(Or you can use JEdit or BlueJ.)

The window contains a line drawn by the statement:

 g.drawLine(0,0,300,300);

In technical terms this means call the method drawLine for the graphics object g, specifying the end points of the line as 0,0 and 300,300. The full meaning of this will become clear in time but it should be obvious that drawLine means draw a line using the start and end points specified. The task of actually drawing the line is performed by the graphics object, without you needing to know how that actually happens. The punctuation (dot, commas and semi-colon) must be present - when you write a drawing program try leaving some of them out and see what happens!

Drawing lines works much the same way as drawing on a piece of graph paper. Notice that the diagonal line slopes from top to bottom, left to right. The co-ordinate of the top left of the window is (0,0), while the co-ordinate at the bottom right is (300,300). Based on this you should be able to work out how to draw a line in any position (just like drawing on graph paper, except you have to remember that (0,0) is at top left not bottom left).

This window will remain on the screen while the program is still running. To stop the program click the Quit button at the bottom of the window. Clicking the button generates an event that the program responds to and it will stop running. Alternatively, the program will stop if you click the window frame close control (providing the window manager of the operating system you are using supplies one). Programs can also be stopped by typing Ctrl-C in the terminal window, if they were started from the command line.

If you read the comment lines in the program carefully you will see the things that you can change. In particular, look for the part where it says:

// You add/change the statements here to draw
// the picture you want.

To draw something different you add or edit statements here. For example, to draw a line from bottom left to top right change the statement:

g.drawLine(0,0,300,300);

to:

g.drawLine(0,300,300,0);

Other Drawing Methods

What else can be drawn? The following is a list of some of the possibilities:

  • g.drawArc(x, y, width, height, startAngle, arcAngle). Draw an arc inside the rectangle with top left corner at (x,y) and size given by width and height.
    startAngle is the angle in degrees that specifies where the arc starts (0 is the 3 o'clock position).
    arcAngle is the angle in degrees that specifies the end of the arc, relative to startAngle.
    Don't follow this? Write a test program and experiment!!
  • g.drawOval(x,y,width,height). Draw an oval inside the rectangle with top left corner at (x,y) and size width by height.
  • g.drawRect(x,y,width,height). Draw a rectangle with top left hand corner at (x,y) and size width by height.
  • g.drawString(text, x,y). Display the text at position (x,y). The text is specified as a string in double quotes, for example:
    g.drawString("Hello",40,40).

If you want know more, visit the online Java documentation and look for class Graphics. On the local CS web this can be seen at: http://www.cs.ucl.ac.uk/teaching/java/javadoc/index.html. At first sight this documentation will appear complex and unfriendly. But don't be put off, over time you will make sense of it and find it becomes an invaluable source of information.

Example Drawing Question and Answer

Example 1. Write a drawing program to display an octagon.

Problem solving steps:

1. Do you understand the question? Study it to make sure you understand what you are required to do. Don't waste time answering the wrong question!

2. How many sides does an octagon have? Answer: 8.

3. To draw an octagon you need to make two decisions:
i) How large it will be, and hence the length of each side.
ii) The position it will be drawn at.

4. Then you need to work out the coordinates of where each side of the octagon starts and ends. Good old trigonometry comes into play to determine the coordinates. But remember that an octagon is a symmetric shape so only a small number of coordinates need to be calculated the hard way, the rest are just offsets from those already calculated. Always look for short-cuts!
(It would be a good idea to double check you can work out the coordinates yourself — have I got those in the example code correct?)

5. Copy the drawing program code, do the renaming as described and write 8 drawLine statements to display the lines using the coordinates you calculate. Don't forget to save the code in a properly named file.

6. Compile the program, fixing any compilation errors by repeated editing and re-compilation.

7. Run the program and check it displays the correct result:

8. If the result is not correct then double check everything. If there is no obvious problem, go back to step 1 and work you way through the steps again. Question and check everything. All too often the thing you think must be correct is wrong!

Don't worry if a program doesn't work first time - they never do! An important part of programming is to persevere. Eventually the problems will be sorted out but it can take time. This is normal.

The statements to draw the octagon are (the rest of the program will not be repeated):

     g.drawLine(60,25,110,25);
     g.drawLine(110,25,145,60);
     g.drawLine(145,60,145,110);
     g.drawLine(145,110,110,145);
     g.drawLine(110,145,60,145);
     g.drawLine(60,145,25,110);
     g.drawLine(25,110,25,60);
     g.drawLine(25,60,60,25);

Notice that each statement is on a separate line and ends with a semi-colon.

Program Presentation

The text of a program should always be presented neatly and made as readable as possible. Program code is primarily read by people (you!) so make sure it communicates effectively:

  • Don't attempt to cram everything into the minimum amount of space - it doesn't make any difference to the speed of the program when it is run!
  • Use blank space and empty lines to layout the program code neatly.
  • Use indentation to reflect the structure of the program (look at the code of the drawing program).
  • Line up the start of lines and opening/closing brackets.
  • Always include the comments at the start of the code. Use more comments if more explanation is needed elsewhere in the program, but don't use them to state what is obvious from reading the code.

If you ask the demonstrator to give feedback on messy code, you will be asked to tidy it up first.


Core questions

Q1.1 Type in the following Java program, compile it and then run it.

// Written by <your name and date>
// This program displays some useful information.
class MyProgram 
{ 
  public void displayMessage()
  {
    System.out.println("This is my first Java program") ;
    System.out.println("It WORKS!!");
  }

  public static void main(String[] args) 
  { 
    // Create an object and tell it to do something
    MyProgram prog = new MyProgram();
    prog.displayMessage();
  }
}

A line containing System.out.println is referred to as an output statement, and is used to display text on the computer screen. Again you will have to take as given the structure of an output statement but you can edit the text between the double quotes to output anything you like.

Hints: Use two windows, one for editing and one for typing commands. When you complete some editing, save the file you are working but don't quit the editor - leave it running for the next lot of editing you need to do. Switch to the other window to issue commands.

Don't forget, the program must be saved in a file called MyProgram.java.
Compile the program using javac, run it using java.

Ask the demonstrator if you need help.

Have you started to organise your filestore? Where did you save the .java file?
For each set of exercises it would be a good idea to create and use a new directory.

Once you have got the program working try editing it to deliberately introduce errors. For example, remove a semi-colon, delete a bracket or change the spelling of one of the words making up the program. Observe the error messages you get when you try to compile the modified program. At first they may not make too much sense but will become familiar! Learn what each error message means and how to resolve the problem reported.

After you have finished experimenting, restore the program to its working condition.


Q1.2 Modify the program in question 1.1 to display the address and phone numbers of the Computer Science Department (hint: look at the web page http://www.cs.ucl.ac.uk). Use a separate output statement for each line of the address. Don't forget that each output statement should end with a semi-colon.

What happens if you change println to print in the output statements? Try it and see.

You will need to give your program a new name and save it a new file, otherwise you will overwrite your answer to Q1.1.


Q1.3 Copy (copy and paste from the web page version of these exercises) the drawing program code presented in the introduction. Save it into a file; remember how the file should be named? Then compile and run the program. Make sure the line displayed is the same as the one in the picture.


Q1.4 Modify your drawing program to draw a hexagon (6 sides). Don't forget to change the name of the drawing program and save it to a new file, otherwise your answer to 1.3 will get overwritten.


Q1.5 Write a drawing program to draw two rectangles:
One with with top left corner at (30,30) and horizontal sides of length 90 and vertical sides of length 45,
and another with top left corner at (150,40) and horizontal sides of length 60 and vertical sides of length 150.

Draw the first rectangle with drawLine and the second with drawRect.


Q1.6 Write a drawing program to draw an square inside a circle, such that the corners of the square touch the circle.

Use drawArc to draw the circle.


Q1.7 Write a drawing program to draw a simple picture of a the UCL dome. This will need a longer sequence of drawing commands. Don't forget to make use of other drawing shapes such as rectangles and circles. Plan your drawing before trying to write your code.


Additional questions

Q1.8 Write a drawing program to draw a series of ovals of increasing size. Use drawOval for this.


Q1.9 Write a drawing program to display the CS department address (see the CS web page at http://www.cs.ucl.ac.uk). Each part of the address should appear on a separate line in the normal way.

Use drawString to do this.


Q1.10 Create a drawing program to draw a bar chart with labels. This will need quite a long list of drawing commands.


Q1.11 Write a drawing program to draw filled shapes using fillRect, fillArc, fillRoundRect and fill3DRect. Find out about these by looking at the online Java documentation on class Graphics (http://www.cs.ucl.ac.uk/teaching/java/javadoc/index.html)


Q1.12 Write a drawing program to draw a sine wave. A method to compute sin is available in the Java class libraries and is called Math.sin. More information is available in the Java documentation. You should know how to work with radians...


Q1.13 Write a drawing program to draw any picture you like using as many features of class Graphics as possible.


Hard Questions

These questions are challenges. Try searching on the web for information - there are lots of interesting websites and examples to be found. Also, discuss these questions with your tutor.

Q1.14 Write a drawing program to draw a fractal shape using a recursive algorithm, like this one:

 

Note that the shape of the sub-elements reflect the shape of the whole.


Q1.15 Write a drawing program to display the mandelbrot set in colour. Add as many user interface features as you like. Allow the user to zoom in on interesting areas.

Drawing a basic Mandelbrot is actually quite straightforward and needs only a few lines of code. When working on this question get a basic working program first and then extend it.

A Mandelbrot looks like this:

Search the web for an explanation of what a Mandelbrot is and how to draw one.


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