COMP1400 – Programming for Designers

Class announcements for Programming for Designers

COMP1400 – Programming for Designers random header image

Tut Wk 9 – Classes and Lists

Posted by on September 16th, 2012 · Lab, Uncategorized

Classes

Consider a database of student records for the university. What kind of data would be associated with each student?

  • Download the Lab9 BlueJ project. It defines a new class Student which contains some student information
  • Create students a number of students in BlueJ. Use the Inspector to examine their fields.
  • Use the getName() method to access the student’s name.
  • Write your own accessor methods to get the address and year enrolled.
  • Add a field to record the student’s gender. Update the constructor to initialise this value appropriately using a parameter. Add an accessor method.
  • Add a field to record the student’s age. Update the constructor to initialise the age to the default value of 18.
  • Add a second constructor that allows you to specify an age other than the default.
  • Add a static final constant to the class for the default age, to avoid using 18 as a magic number in your code.

Consider designing a class representing a car in a database for a used car lot.

  • What kinds of data would be recorded about each car?
  • What are the types of this data?
  • Write a Car class representing an entry in this database. Give it:
    1. Fields recording the above data.
    2. A public constructor.
    3. Public accessor methods to read the data.

Lists

  • Create an ArrayList of strings in BlueJ using the Tools > Use Library Class… menu.
  • Right click on the list object to see the public interface, the list of available methods.
  • Double click on the object to inspect the private implementation, the fields internal to the list object.
  • Call the size method to check that the list is initially empty.
  • Call the add method to add some names to the list.
  • Use the inspector to see how the fields have changed.
  • How does the elementData field change as you add names to the list? What happens if you add more than 10 names?
  • Use the get method to read items off the list. What happens if you try to read an item beyond the end of the list? Explain the message you receive.

Create a new class called StringUtils with the following methods:
public String findLongest(ArrayList)

This method should search through a list of strings to find the longest one. You can use the length() method on the String class to find this value.

public ArrayList findStartsWith(String prefix)
This method should search through the list and collect all strings that start with the given prefix. You can use the startsWith() method to help you.

Week 8 Tut – Objects

Posted by on September 9th, 2012 · Lab
  1. Create an instance of the java.util.Random class in BlueJ using the Tools > Use Library Class… option.
  2. Right click on the object created to see its methods. Try running some of them. What do they do?
  3. Read the Java docs for the Random class.
  4. Which method would you use to:
    • Simulate a fair coin toss?
    • Simulate a (six-sided) dice roll? What about ten-sided? Twenty-sided?
    • Simulate a biased coin that shows heads 67% of the time?
  5. Open the Code Pad and do the following
    • Write a command to construct a Random object with the seed 200 and assign it to a variable.
    • Call nextInt() several times on the object you created.
    • Create a second object with the same seed and call nextInt() on it too. Explain the result.
  6. Write a method rollDice(int number, int nSides) which returns the total result of rolling the number dice with nSides sides.

    So for example rollDice(3, 6) should return the result of rolling
    3 six-sided dice (adding to a number between 3 and 18 inclusive).

  7. Write a method selectRandom(String[] names) which returns a randomly selected name from the given array. Each name should be selected with equal probability.
  8. Challenge: Write a method shuffle(String[] names) which takes an array of names are returns a copy of the list with the names randomly rearranged. Each possible should be returned with equal probability.

    So for instance, given the code:

    String[] names = {"Malcolm", "Troy", "Sim"};
    String[] shuffled = shuffle(names);

    The following return values should be equally likely:

    1. {“Malcolm”, “Troy”, “Sim”}
    2. {“Malcolm”, “Sim”, “Troy”}
    3. {“Troy”, “Malcolm”, “Sim”}
    4. {“Troy”, “Sim”, “Malcolm”}
    5. {“Sim”, “Troy”, “Malcolm”}
    6. {“Sim”, “Malcolm”, “Troy”}

Assignment 2

Posted by on August 23rd, 2012 · Assignments

NOTE: This assignment is due by midnight Friday Sunday Sept 16 (the end of week 8). [Corrected]

For this assignment you will write a program that implements Conway’s Game of Life. The board is a rectangular array in which a cell is designated as either live or dead. A few simple rules tell you how to create a new generation (i.e. a new board) based on the old one.

  1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, as if by overcrowding.
  4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

You can see an animation of the game at this web site. We will not build a graphical display like that one (although that animation is written in Java too). Instead, we will print each generation to the console For example,

..............................
..............................
..............................
..............................
..............................
..............................
..............................
..............................
..***.........................
....*.........................
..*...........................
..............................

You will find a project file for the assignment here. It contains methods for reading in an initial board, like the one above. This is stored in the README.TXT file that is in the project folder. You can change this and experiment with different starting patterns. Try as many arrangements as you can to test your code thoroughly.

Task 1

The project also has the main method that plays that game. You are required to write three methods. This simplest one is to print the board. Note that you MUST print it out exactly as above.

A board is represented as a 2-dimensional boolean array:

boolean[][] board = new boolean[numberOfRows][numberOfColumns];

Your print method is called as follows:

public static void printBoard(boolean[][] board)

The method should print each row of the array on separate lines with a ‘.’ representing a false cell and a ‘*’ representing true.

Task 2

The second method you must write is to count the live neighbours of a cell.

public static int countNeighbours(boolean[][] board, int row, int col)

Given a board (i.e. a 2D boolean array) and a row and column position, count the number of immediately surrounding cells that contain the value true. The table below shows the index values of the neighbours of the cell where i is the row number and j is the column number (starting from zero).

i-1, j-1 i-1, j i-1, j+1
i, j-1 i, j i, j+1
i+1, j-1 i+1, j i+1, j+1

Your method should visit each of the surrounding cells and accumulate a count of the cells that contain true, i.e, the cell is live. Note that you do not count the cell itself. If a cell is on the edge of the array (i.e. some of its neighbours are out of bounds), only count the cells that are within the array.

Task 3

The third method you must write is:

public static boolean[][] nextGeneration(boolean[][] board1)

The only parameter to the method is a board (i.e. a 2D boolean array). For each cell in the array (i.e. for each column position in each row), apply the four reproduction rules, given above, to create a new board representing the next generation. To do this, you must declare a new array that is the same size as the old one. As you apply the rules to a cell in the old array, you update the corresponding cell in the new array. That is, you must not change the original array.

WARNING: The Game of Life is a popular programming exercise and you will find many versions of it on the web. While you may use these to get an idea of how to write your own program, your code must be your own. Plagiarism is not allowed and will be heavily penalised.

Submission

  • From within your assignment 2 BlueJ project, select Project -> Create Jar File…
  • In the Dialog Box that appears:
    1. Set “Main Class” to none
    2. Ensure “Include Source” is checked
    3. Leave “Include Bluej project files” unchecked
    4. Press “Continue”
    5. Save the filename as “Assignment2.jar”
  • Open a web browser and go to the give web site
  • Log-in with you Z-Pass
  • Either enter “COMP1400″ in for the course and press “Search for Assignments”.
  • Select “Assignment2″ from the next drop down menu and press “Upload my Assignment”
  • Accept the student declaration
  • Press “Choose File” and select the “Assignment2.jar” file that you saved in step 4
  • Press “Submit my Files”
  • Wait for the page to completely load. Then carefully read the output. If the assignment is successful you should see the following lines:
    ================================================
    Checking your submission...

    Checking for Life.java
    Live.java Compiled Sucessfully

    All files are OK
    ================================================
    If the page doesn’t load properly, that is OK just submit the assignment file again.
    If you don’t get the above output check the output to see what went wrong and resubmit.

Submission notes:

You can submit as many times as you wish, even after the deadline. Only your last submission will be marked.
Make sure you name everything the as instructed, including the classes and the submission file or the submission will not work.
If you have any problems with submission, email the class account. Include exact details of any error messages you get.

Tutorial Wk 7 – ASCII Art

Posted by on August 22nd, 2012 · Lab

In this tutorial we will be working with 2D arrays to do some image manipulation.

Download the BlueJ project ASCIIArt.zip. Inside you will find a class that contains the method readImage(String url). This method takes the URL for any image on the web and converts it into a 2D array of integers. Each entry in the 2D array represents the brightness of one pixel. The values range from zero (black) to 5 (white). Entries are arranged in width by height order so an array like:

{{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 5, 0, 0, 0, 0, 0, 0, 0}
{0, 5, 5, 5, 0, 0, 0, 0, 0},
{0, 5, 3, 3, 5, 5, 0, 0, 0},
{0, 5, 3, 3, 3, 3, 5, 5, 0},
{0, 5, 3, 3, 5, 5, 0, 0, 0},
{0, 5, 5, 5, 0, 0, 0, 0, 0},
{0, 5, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0}}

represents a grey triangle (the ‘3’ pixels) with a white border (the bright ‘5’ pixels) pointing to the right on a black background (the ‘0’ pixels).

Your tasks:

  1. Write a method to draw an image on the console using ASCII art. That is, each pixel of the image is drawn as a character according to the following table:
    Brightness Character
    0 'X'
    1 '8'
    2 'o'
    3 ':'
    4 '.'
    5 ' '

    So the triangle above would be rendered as:

    XXXXXXXXX
    X XXXXXXX
    X   XXXXX
    X ::  XXX
    X ::::  X
    X ::  XXX
    X   XXXXX
    X XXXXXXX
    XXXXXXXXX
    


  2. Write a method to invert an image, so that bright pixels are converted to dark and vice versa. It should input an image and return an inverted copy.
  3. Write a method to flip an image horizontally. It should input an image and return a flipped copy.
  4. Challenge: Write a method to rotate an image clockwise. It should input an image and return a rotated copy.

More arrays

Posted by on August 19th, 2012 · Lab

This week’s tut covers two very common activities in programming: mapping and filtering.

  • Write a method mapDouble which takes in an array of integers and returns a new array containing the double of each entry in the first array. Eg:

  • int[] data = {1, 3, 4, 2, 0, 5, -2};
    int[] doubled = mapDouble(data);

    The returned array doubled should contain {2, 6, 8, 4, 0, 10, -4}.

  • Write a method filterEvens which takes in an array of integers and returns a new array containing only the even values. Eg:

    int[] data = {1, 3, 4, 2, 0, 5, -2};
    int[] evens = filterEvens(data);

    The returned array evens should contain {4, 2, 0, -1}.

    Hint 1: You can check if a number is even by testing if the remainder when dividing by 2 is zero.

    Hint 2: You will probably need to do this in two stages. First count the number of even entries to work out how big the returned array should be. Second, go through the list copying entries. If you have trouble writing this in code, try working through examples by hand on paper.

Tutorial Wk 5

Posted by on August 9th, 2012 · Lab

If you did not finish all the exercises from last week’s lab, try to finish them off this week. If you have already completed those exercises, try these ones.

Exercise 1. Write a method that accepts two arguments, an integer and an array of integers. Assume that the numbers in the array are sorted in ascending order. Your method should return a new array that is one element longer than the first array and with the first argument inserted into the array, in the correct position.

Exercise 2. Now suppose that we want to insert the number into the same array, rather than creating a new one. What would you have to do? What complications arise in this version and how would you handle them?

Assignment 1

Posted by on August 6th, 2012 · Assignments

Due: 11:59pm Friday 17 August (i.e. the end of week 5)

This assignment is about arrays. You will write three methods to manipulate arrays. The first two are easy. The third one will require more thought about the design. You will submit the assignment using the CSE give system (see below).

Download the BlueJ project, Assignment1.zip. It contains three methods. You have to write the code that goes inside them.

The fist method finds the average of the elements of an integer array:

public double average(int[] data)

That is, given an integer array, data, calculate the average of its elements are return the average value. For example, the average of {1, 3, 2, 5, 8} is 3.8.

The second method is:

public int countInRange(int[] data, int lo, int hi)

For this, you have to count the number of elements of the array, data, that lie in the range lo to hi inclusive, and return the count. For example, if data is the array {1, 3, 2, 5, 8} then the call

countInRange(data, 2, 5)

should return 3 because there are three elements, 3, 2 and 5 that lie in the range 2 .. 5.

The third method is:

public int mode(int[] R)

This calculates the mode of the array elements. The mode is the value that occurs most frequently. For example the mode of the array

{1, 43, 12, 56, 88, 1, 12, 90, 90, 12, 1, 1, 1, 12, 90, 12, 12, 78}

is 12 because the value 12 occurs 5 times in the array, which is more than any other value. Note that, in general, the mode may not be unique as it is possible that more than one value will occur with the same frequency. However, for this assignment, we will assume that the mode will be unique, i.e. there will only be one value with the highest occurrence.

HINT: You can assume that the values in the area are limited to the range 1 .. maxValue, where maxValue is some positive integer, like 10 or 100. This assumption allows you to do the counting relatively easily with clever use of arrays.

Submission instructions

You will submit your assignment to the Give automated marked system.

  1. From within your assignment 1 BlueJ project, select Project -> Create Jar File…
  2. In the Dialog Box that appears:
    1. Set “Main Class” to none
    2. Ensure “Include Source” is checked
    3. Leave “Include Bluej project files” unchecked
    4. Press “Continue
    5. Save the filename as “assignment1.jar
  3. Open a web browser and go to the give web site
    1. Log-in with your Z-Pass
    2. Enter “COMP1400″ in for the course and press “Search for Assignments”.
    3. Select “Assignment1″ from the next drop down menu and press “Upload my Assignment
    4. Accept the student declaration
    5. Press “Choose File” and select the “assignment1.jar” file that you saved in step 4
    6. Press “Submit my Files
    7. Wait for the page to completely load. Then carefully read the output. If the assignment is successful you should see the following lines:

      Checking your submission...
      Checking for relevant classes...
      All files are OK

      If the page doesn’t load properly, that is OK just submit the assignment file again.
      If you see the final line, everything is good. Otherwise check the output to see what went wrong and resubmit.

Submission notes:

You can submit as many times as you wish, even after the deadline. Only your last submission will be marked.
Make sure you name everything the as instructed, including the classes and the submission file or the submission will not work.
If you have any problems with submission, email the class account

Tutorial – Wk4

Posted by on August 2nd, 2012 · Lab

This week, you will download the BlueJ project Week4.zip and write methods to manipulate arrays. Two methods are given to you complete. You don’t have to do anything to them.

The method readArray

public int[] readArray()

reads a list of numbers, one per line, ending with a blank line, and returns an array containing the numbers. Don’t try to understand the details of this method. It uses things that you’ll learn about later.

The method printArray takes an integer array parameter and prints it to the terminal

public void printArray(int[] R)

The project provides templates for other methods that you have to write. Your job is to work out the code that goes inside them.

The first method, arrayAdd, takes two arrays as parameters and returns a new array that is the sum of the first two.

public int[] arrayAdd(int[] R1, int[] R2)

The addition of two arrays yields an array whose elements are the sum of the corresponding elements in the parameter arrays, i.e.

R1[0] + R2[0], R1[1] + R2[1], R1[2] + R2[2], ....

The dotProduct of two arrays returns a single integer.

public int dotProduct(int[] R1, int[] R2)

It is found by multiplying corresponding elements and adding them all up, i.e.

R1[0] * R2[0] + R1[1] * R2[1] + R1[2] * R2[2], ....

Finally, you should write a method, main,

public void main()

that reads two arrays, then:

calls arrayAdd and calls printArray to print the resulting array
calls dotProduct and prints the result

Tutorial Wk 3 – Data types

Posted by on July 27th, 2012 · Lab

The exercises below use the Tut3.zip project for BlueJ.

Data types

What data type would you use to represent the following values? Why?

  1. The length of a piece of string.
  2. The number of students at UNSW.
  3. A person’s age.
  4. The mass of the sun.
  5. The exact number of stars in the Milky Way.
  6. The mathematical constant π.

Expressions

What are the value and type of the following expressions? Test your answers by typing them into the Code Pad in BlueJ. Can you explain the result?

  1. 5 / 2
  2. 5 % 2
  3. 5.0 / 2
  4. 5 / 2.0
  5. 5.0 / 2.5
  6. 5.0f / 2
  7. 1.5 % 1
  8. 1 / 0
  9. 1.0 / 0
  10. 10000000000 + 1
  11. 10000000000L + 1
  12. 10000000000.0 + 1
  13. 10000000000.0f + 1

Circle area

The circleArea method in the Tut3 class calculates the area of a circle with a given radius.

  • Create a new Tut3 object and try calling this method with different input values.
  • Add breakpoint on the first line and step through the code. Watch the ‘local variable’ panel to see variables being created and change value.
  • Change the method to calculate the area of an ellipse of given width and height

Hand shaking

If there are five people Alan, Bel, Cameron, Dan, and Emily in the room and they each have to shake hands with everyone else, how many handshakes occur? What if there were 10 people? What if there were only two? Work out a general formula.

Complete the ‘handshakes’ method in the Tut3 project to use your formula to compute the number of handshakes for a given size group.

The Math Class

For more complicated mathematical expressions, Java has a lot of built in methods in the Math class. Take a look at the documentation to see what is available. Try typing the following
in CodePad. Explain the results.

  • Math.sqrt(2.0)
  • Math.round(3.1)
  • Math.round(3.7)
  • Math.min(1, 2)
  • Math.max(1, 2)

Textbook

Posted by on July 17th, 2012 · Uncategorized

It has just come to our attention that the new edition of the textbook costs almost twice as much as the old one! If you can get your hand on an old copy of the 4th Edition text this should be fine for everything we will be doing in the subject.