COMP1400 – Programming for Designers

Class announcements for Programming for Designers

COMP1400 – Programming for Designers random header image

Lab Week 4 – Loops and Arrays

Posted by on August 15th, 2013 · Lab

In this lab, we’ll practice creating a new BlueJ project from scratch. Use the “New” menu item to make a new class. Call it Week4. All the exercises below can be done in the same class file. You may not be able to finish all the questions during the lab time. Make sure that you do at least one question from each section in the lab and finish the rest as homework.

Basic Output

1. Write a method that prints the string “Hello World” 8 times. The output should be:

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

2. Write a method that prints your name, age and favourite number, using integers for the numbers. For example:

My name is Fred, I am 18 years old, my favourite number is 2.

Simple Calculations

1. Write a method, which takes one parameter n and returns the number squared.

2. Write a method, which takes three parameters a, b and c to calculate the area of a triangle using Heron’s formula: area = sqrt(s(s-a)(s-b)(s-c)). Where s is the “semi-perimeter” given by s = (a+b+c)/2. The sqrt can be calculated by Math.sqrt()

3. Write a method that performs a calculation that you learnt in high school mathematics. The method should take as parameters any variables of the calculations and return the result of the calculation.

4. Write a method that takes a 4 digit number and then prints the number of units, tens, hundreds and thousands. For example:

Number: 1234
4 units
3 tens
2 hundreds
1 thousands

Using conditions

1. Write a method that takes in one parameter year and prints “This is a leap year”, if the year is a leap year or “This is not a leap year” if it is not. Recall that years are leap years if they are divisible by 4. Except years divisible by 100 are not leap years unless they are also divisible by 400.
HINT: the code x % y returns the remainder when x is divided by y

2. Write a method that takes three integers and prints them out in increasing order.

3. Write a method which takes in three real numbers a, b and c representing the coefficients of a quadratic equation ax2 + bx + c and uses the quadratic formula to determine one solution of the equation ax2 + bx + c = 0. Use an if statement to ensure that the program works correctly for all numeric input.

4. Write a method that takes a single integer, n between 0 and 9 and prints out the word for that number. For example

Number: 0
zero
Number: 1
one
Number: 9
nine

Using Loops

1. Write a method, which takes two parameters n and pow and returns the value of npow

2. Write a method with a while loop that prints out the numbers from 1 to 10 and their squares.

3. Change your method in question 1 to use a for loop.

4. Modify your method in question 2 so that is prints “Number is even”, if the number (or its square) is even. Otherwise print “Number is odd”.

5. Write a method that takes one parameter n and outputs an n x n square of asterisks. For example

Square: 5
*****
*****
*****
*****
*****

6. Write a method that takes one parameter n and outputs an n x n triangle. For example

Triangle: 5
    *
   **
  ***
 ****
*****

7. Write a method, which takes one parameter, a positive integer n and prints all the factors of n. For example:

n: 1001
The factors of 1001 are:
1
7
11
13
77
91
143
1001

Using Arrays

1. Write the method, void stars(int[] values) which, for each element of values prints out the number of asterisks corresponding to the integer. For example:

 values: {3, 2, 1, 5, 5, 3, 1, 0, 2}
***
**
*
*****
*****
***
*

**

2. Write the method, boolean isIncreasing (int[] values) which returns true if the values in the array are in increasing order. It should return false otherwise

 

Lab Week 3 – Data Types

Posted by on August 8th, 2013 · Lab

This week’s lab exercises are concerned with data types, which were introduced in last week’s lectures.

Feedback on your progress

At the start of the lab, you’ll be given a short quiz on writing simple methods. This shouldn’t take more than 15 minutes.

Each week, we will ask you short quiz questions to encourage you to do some preparation before the lab. The intention of the quizzes is to give you quick feedback so that you know if you understand the material in the course so far and to encourage you to prepare for the labs by reading over the lecture material from the previous weeks.

You’ll be given a mark for each quiz just to make sure that you take them seriously, but note that they contribute only a small part to your final assessment (about half of your lab mark, the other half from your attempts at the lab exercises). Your answers will be marked as either satisfactory or unsatisfactory by your tutor during the lab. If you have a good reason for missing a quiz, talk to your tutor about making it up.

After completing the quiz, you should attempt the exercises below using 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? Work these out on paper and then 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
  14. int x = 10;
  15. x = x + 2;
  16. int y = 3;
  17. int z = x + y + 1;
  18. x = x+ 2;

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. The area of an ellipse is π × height × width / 2. You can use the value 3.141592 for π or use Java’s math library definition, Math.PI.

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)

If-statements

Assume we have declared an integer variable x. Write an if-statement that will print “one” if the value of x is 1, “two” if the value of x is 2 and “something else” if the value x is some other value.

Lab Week 2 – Getting to know BlueJ

Posted by on August 1st, 2013 · Lab

There are three tasks for this week’s lab:

  1. Activate your CSE account.
  2. Write your first program!
  3. Play with BlueJ

Activate your CSE account

The first thing we will do in this week’s lab is activate your CSE account, if you haven’t done so already.

  1. Login as ‘newuser’
  2. Follow the prompts to activate your account.
  3. Write your new username and password somewhere so you don’t lose it.
  4. Log out.
  5. Click on the ‘Session’ button on the login screen.
  6. Select ‘Gnome’.
  7. Login with your new username and password. (Sometimes it can take up to 30mins for your account to be activated. If this is the case, complete the next activity and then come back to this step.)
  8. When asked, click ‘Make Default’.

Write your first program.

Need help with this exercise? Click here.

This is an exercise in breaking down a task into a sequence of simple instructions. Work in pairs. Your tutor will give each of you a small, incomplete pack of cards.

  1. Shuffle the deck.
  2. Go through the deck to find the smallest card.
  3. On a sheet of paper, write a set of instructions so that someone else can repeat the same procedure. Assume that they are very stupid and need to have ever last detail spelled out.
  4. Test your instructions on different size decks:
    • What if there is only 2 cards in the deck? Or only one? Or none?
    • What if all the cards in the deck were the same?
  5. Swap programs with another pair and check their code. Was it the same as yours?
  6. Consider: What are the objects in your program? What are the classes? What fields do they have? What methodsdo they provide?
  7. Now try writing instructions to sort the entire deck into order.

Experiment with BlueJ

Experiment with the BlueJ projects we saw in lectures.

  1. Login with your CSE login and password set up earlier
  2. Download the Turtle.zip
  3. Unzip this file to create the BlueJ project.
  4. Start BlueJ
  5. Select ‘Open Project’ from the File menu and open the ‘Turtle’ project.
  6. Create a new ‘MyTurtle’ object by right clicking on the MyTurtle class and selecting new MyTurtle()
  7. Give your turtle a name and press OK.

Simple shapes

  1. Right click on the red MyTurtle object and select the void drawSquare(int sideLength) method.
  2. Enter a side length of 100 and press OK.
  3. Observe what happens in the World window.
  4. Try drawing squares of different sizes.
  5. What direction does the turtle face before and after you call the method?
  6. Double-click on the MyTurtle class to open the source-code.
  7. Read the drawSquare method. Can you explain why the turtle has a different direction after the method is called?
  8. What could you do to fix this so the turtle is facing the same way before and after the method?
  9. Change the code so that it draws a triangle instead of a square.

Using the debugger

  1. Read the method drawPolygon and try to understand how it works.
  2. Run it with different parameters to see if it does what you expect.
  3. In the source window, click on the line number for the line “if (numberOfSides < 3) {“. A little red stop sign should appear.
  4. Run the method again with numberOfSides set to 6 and sideLength set to 100. The Debugger window should appear.
  5. Press the Step button and watch how the program steps through the code.
  6. Run the method again with numberOfSides set to 2. Can you predict what will happen?

Spirals

  1. Read the method drawSpiral and try to understand how it works.
  2. Try drawing a spiral with length = 10 on a piece of paper following these instructions.
  3. Use the debugger to step through the method. Does it do what you expected?
  4. Change the line ‘length = length – 2‘ to ‘length = length – 4‘. How will this change the spiral? Run it and see.
  5. Change the line to ‘length = length + 4‘. What happens now? Why?

 

Welcome to COMP1400/INFS1609/INFS2609 13s2

Posted by on July 31st, 2013 · Announcements

This course introduces you to the foundations of the programming discipline, which underlies most technical subjects such as software design, data management and algorithms. It will involve both a theoretical component (e.g. learning about basic programming concepts like loops, arrays and functions) as well as a practical component (e.g. implementing simple algorithms in a computer laboratory). The course also provides a first step towards learning the principles of object-oriented design and programming through the use of the Java programming language.

The course is suitable for students with no prior programming experience. It is particularly targeted at IS students as it relates to a number of core concepts that are essential in understanding the technologies behind information systems in business without getting overmuch into low-level technical details.

All students should ensure they have read the Course Outline.

 

Lab Wk 12 – Uno Game

Posted by on October 7th, 2012 · Uncategorized

Download the Uno Game BlueJ project shown in the lecture.

Constructors

Use the debugger to watch how cards are constructed:

  1. Set a breakpoint in the WildDrawCard constructor (line 17).
  2. Create a new WildDrawCard by calling the constructor..
  3. Use the ‘step into’ button to step through the code. Observe how the super() call works.
  4. Repeat this process for the other kinds of cards.

Set up a game:

  1. Call Game.makeStandardDeck() to create a deck (ArrayList) of cards.
  2. Press the Get button to save this deck in a variable.
  3. Call the Game constructor, providing this deck as a parameter.
  4. Call the deal() method on the game you created to deal the cards.

Inheriting methods

  1. Create a selection of cards from the different card classes.
  2. Right-click on each card to observe the methods it implements and the methods it inherits.
  3. Where is the canPlay() method implemented on each card type?
  4. Where is the play() method implemented on each card type?
  5. Set a breakpoint in WildDrawCard.play() (line 26).
  6. Create a WildDrawCard and call its play() method. Use the debugger to step through the code.
  7. Observe the order the code is executed.

Add a new card type

  1. Change the rule for the NumberCard so it can only be played on another NumberCard of value one more or one less that itself. (i.e. a 5 can be only played on a 4 or 6). Numbers should wrap around, so a 0 can be played on a 9 and vice-versa.
  2. Create a Transfer card class which transfers 2 random cards from the player to the previous player.
  3. Add a new Reverse-Draw card class which reverses the direction of play then causes the next player to draw. Does it have any code in common with other cards? What class would it be best to inherit from?
  4. Create your own card types.

Wk 11 – Wumpus with Interfaces

Posted by on October 3rd, 2012 · Lectures

I finished re-implementing the Wumpus game using the Hazard interface we discussed in today’s lecture. You can find the complete source here.

I have also uploaded revised slides containing the changes I made during the lecture.

Tut Wk 11 – Wumpus

Posted by on October 1st, 2012 · Lab

Download the Wumpus game shown in lectures.

Examine the code try to follow how it works. Make the following changes to the game:

  1. Rearrange the rooms so that are in a 4×5 grid.
  2. Make it so that the wumpus needs to be shot more than once (you choose how many times) to be killed. Each time it is shot it runs to a random neighbouring room (not the one the player is in).
  3. Add a new ‘hazard’ – a Trader who gives the player more arrows. Consider:
    • What ‘warning’ sound is heard if the trader is nearby?
    • What happens when the player enters the trader’s room?
    • Where does the trader fit in the sequence of hazards?
    • What should happen if the player shoots the trader?
  4. Give the player more ‘lives’. So if they die (by pit or wumpus) they reappear in a random room.

Long weekend and Tut 11

Posted by on September 25th, 2012 · Lab

If you are in one of the Monday tutorials, your usual class will not be running next week as it is the long weekend. You are welcome to turn up to one of the other tutorial times:

Tue 10:00 – 12:00 Mabu Lab Elec Eng 455
Tue 14:00 – 16:00 Leaf Lab Mech Eng Undercroft
Tue 16:00 – 18:00 Moog Lab Mech Eng Undercroft
Wed 13:00 – 15:00 Mabu Lab Elec Eng 455

Note: You will not be penalised if you can’t make it to any of these times, however it would be good to attempt the exercises in any case.

Tut Wk 10 – Scrabble

Posted by on September 23rd, 2012 · Lab

Consider the game of Scrabble.

  1. List all the data involved in representing the game. Be thorough.
  2. How might this data be divided into abstract chunks? What idea does each chunk represent?
  3. Draw a flow chart of the game play. Break it up into methods of different levels of detail.
  4. How do these methods associate with the chunks of data above.
  5. Design a collection of classes representing these chunks. What fields and methods do they have?
  6. How many objects of each class will you need to create? How will they connect to each other?
  7. Write the main method of your game. It should:
    1. Create the objects.
    2. Start the game.
  8. Write method signatures for the other methods you will use. Do not write the code, just decide on what the necessary chunks are at each level of detail.
  9. Write “pseudocode” comments in each method describing the steps it should take and the other methods that it should call.
  10. Challenge: Write the complete game.

Assignment 3 – DRAFT

Posted by on September 19th, 2012 · Uncategorized

In this assignment you will be implementing a simple job queue using objects and array lists.

Due date: Midnight Sunday Oct 14 (end of week 12)

Topics covered

This assignment covers the following ideas:

  • OO design: Abstraction and encapsulation
  • Implementing a class with fields, constructors and accessor methods,
  • Handling collections of objects with ArrayLists,
  • Implementing state using fields and mutator methods,
  • Using the null object to represent “nothing”.

The task

You need to implement two classes Job and JobQueue.

The Job class

The Job class is a simple data structure containing:

  • The job name (a String)
  • The duration of the job in seconds (a positive integer).

You need to implement a class called Job with appropriate fields to store this data.

You also need to implement:

  • A constructor: Job(String name, int duration) which initialises the fields to the given values.
  • Accessor methods: getName() and getDuration(). which return the field values.
  • A run() method which prints “JOB COMPLETE: ” followed by the name of the job.
    E.g. The code:

    Job job = new Job("Wash the car.", 100);
    job.run();

    should print:

    JOB COMPLETE: Wash the car.

The JobQueue class

The JobQueue class implements a queue of jobs. When you create the queue it is initially empty. You can add jobs to the end of the queue. You can also add run time to the queue. When you run the queue, any available run time is used to execute jobs in the order they are added. As each job is completed, it is moved to the complete jobs list.

So for example, starting with an empty queue:

  1. Add a job “A” that takes 20 seconds.
  2. Add a job “B” that takes 10 seconds.
  3. Add a job “C” that also takes 10 seconds.
  4. Add 25 seconds to the clock.
  5. Run the queue:
    1. Job A is completed. 5 seconds remain on the clock.
    2. Job B is now the current job.
    3. There is not enough time to complete this job, so the queue stops.
  6. Add another 20 seconds to the clock, making the total 25.
  7. Run the queue:
    1. Job B is completed. 15 seconds remain on the clock.
    2. Job C is completed. 5 seconds remain on the clock.
    3. The jobQueue is now empty, so it stops with 5 seconds left on the clock

You need to implement:

  • The JobQueue class with appropriate fields.
  • A constructor with no parameters than initialises the pending and completed queues to empty and the clock to zero.
  • Accessor methods:
    • getPendingJobs() which returns the list of jobs that have not been completed (including the current job)
    • getCompletedJobs() which returns the list of jobs that have been completed.
    • getCurrentJob() which returns the job at the front of the pending queue, or null if the queue is empty.
    • getClockTime() which returns the amount of time left on the clock (as an integer)
    • getTotalDuration() which returns the total duration of all the pending jobs.
  • Mutator methods:
    • addJob(Job job) which adds a Job to the end of the Queue.
    • addTime(int seconds) which adds the specified number of seconds to the clock.
    • runOne() which runs the first job on the queue if there is enough time on the clock.
    • runAll() which runs all the jobs on the queue in order until it runs out of time.

Sample solution

We are not providing a skeleton solution for this assignment as we will be testing that you are able to write your own method signatures following the description above. However it is important that you follow the specification as closely as possible. To help in this, we have provided a sample solution as a BlueJ project with the source code removed. Please check carefully to make sure your program works exactly the same as the sample solution.

Submission

  • From within your assignment 3 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 “Assignment3.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 “Assignment3″ from the next drop down menu and press “Upload my Assignment”
  • Accept the student declaration
  • Press “Choose File” and select the “Assignment3.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 JobQueue.java
    JobQueue.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.