COMP1400 – Programming for Designers

Class announcements for Programming for Designers

COMP1400 – Programming for Designers random header image

Week 12 Lab – HashMaps

Posted by on October 20th, 2013 · Lab

This week’s tutorial is taken from the textbook, exercises 5.25 – 32 on page 174-175. They are reproduced below.

The task is to implement a simple phone book where numbers are associated with names, both represented as strings. Your phone book should be able to add a new name/number pair and you should be able to lookup a number, given a name.

    HashMap<String, String> phoneBook= new HashMap<String, String>();

initialises the phone book. The following statements add new entries:

    phoneBook.put("Charles Nguyen", "(02) 9392 4587");
    phoneBook.put("Lisa Jones", "(03) 4536 4674");
    phoneBook.put("William H. Smith", "(07) 5488 0123");

Next, we look up an entry:

    String number = phoneBook.get("Lisa Jones");
    System.out.println(number);

We refer to the name as the key because it is used for the lookup. Given the above, answer the following questions. You will need to use the Java API documentation.

  1. Create a class MapTester in a new project. In it, use a HashMap to implement a phone book. You will have to import java.util.HashMap. In this class, implement two methods:
    public void enterNumber(String name, String number)

    and

    public String lookupNumber(String name)

    The methods should use put and get methods of the HashMap class to implement their functionality.

  2. What happens when you add an entry to a map with a key that already exists in the map?
  3. What happens when you add an entry to a map with two different keys?
  4. How do you check whether a given key is contained in a map? Try it in Java.
  5. What happens when you try to look up a values and the key does not exist in the map?
  6. How do you check how many entries are contained in the map?
  7. How do you print out all keys currently stored in a map?

Assignment 3 clarification

Posted by on October 19th, 2013 · Announcements, Assignments

Running the sample solution, one would notice that the JobQueue method runOne() should return a boolean.

Week 12 Quiz: Inheritance

Posted by on October 19th, 2013 · Announcements

For this week’s quiz, the best way to prepare is to complete last week’s lab work and study up on the content it covers.

Week 11 Lab – Inheritance

Posted by on October 12th, 2013 · Lab

The following exercises are taken from chapter 8 of the textbook.

Exercise 8.4 Open the project dome-v2. This project contains a version of the DoME application rewritten to use inheritance, as described above. Note that the classdiagram displays the inheritance relationship. Open the source code of the DVD class and remove the ‘extends Item‘ phrase. Close the editor. What changes do you observe in the class diagram? Add the ‘extends Item‘ phrase again.

 

Exercise 8.5 Create a CD object. Call some of its methods. Can you call the inherited methods (for example, setComment)? What do you observe about the inherited methods?

 

Exercise 8.6 In order to illustrate that a subclass can access non-private elements of the superclass without any special syntax, try the following slightly artificial modification to the CD and Item classes. Create a method called printShortDetailsin the CD class. Its task is to print just the artist and the title of a CD on a line by itself. However, because the titIe field is private in the Item class, it will be necessary to add a public getTitIe method to Item. Call this method from printShortDetails to access the title for printing. Remember that no special syntax is required when a subclass calls a superclass method. Try out your solution by creating a CD object. Implement a similar method in the DVD class to print just the director and title.

 

Exercise 8.8 Open the dome-v2 project. Add a class for games and a subclass for video games to the project. Create some video game objects and test that all methods work as expected.

Database inheritance diagram

 

Exercise 8.12 Assume we have four classes: PersonTeacherStudent andPhDStudentTeacher and Student are both subclasses of PersonPhDStudent is a subclass of Student.

a. Which of the following assignments are legal, and why or why not?

Person p1 = new Student();
Person p2 = new PhDStudent();
PhDStudent phd1 = new Student();
Teacher t1 = new Person();
Student s1 = new PhDStudent();

b. Suppose that we have the following legal declarations and assignments

Person p1 = new Person();
Person p2= new PerSon ();
PhDStudent phd1 = new PhDStudent();
Teacher t1 = new Teacher () ;
Student s1 = new Student();

Based on those just mentioned, which of the following assignments are legal and or why not?

s1 = p1;
s1  = p2;
p1 = s1;
t1 = st;
s1 = phd1;
phd1 = s1;

 

Exercise 8.13 Test your answers to the previous question by creating bare-bones versions of the classes mentioned in that exercise and trying it out in BlueJ

 

Random Guessing Game Exercise

Posted by on October 10th, 2013 · Uncategorized

I have made this additional exercise for students who would like more practice on using Random (along side ArrayLists, Loops and Conditional Statements). Solutions have been provided but it is strongly recommend you attempt the task yourself before checking them.

Random Guessing Exercise:

This will be a game where you choose a range for a ‘secret number’ to be in and then you will try and guess it! You will be able to use hints, show your old guesses and restart the game with a different range when you have won.

For this exercise you will need to create a new class, call it GuessGame. It will have the following fields.

FIELDS:

  • secretNum: Stores the secret number you will be trying to guess (int)
  • guesses: Stores all the guess that have already been given (ArrayList)

For our constructor we want to specify the range in which our secretNum will be. So we want the following parameters for our constructor.

CONSTRUCTOR PARAMETERS:

  • min: The lowest value the secret number can be (int)
  • max: The largest value the secret number can be (int)

Question: What should we do if the user gives us a max that is less than the min?

In order to play our guessing game we need to write the following methods.

METHODS:

  • guessNum: Takes in a number and returns true if it is the same as the secret number, false otherwise. Remember to record the guess made in our ArrayList!
  • higherOrLower: Takes in a number and prints out whether or not the secret number is higher or lower than the input number.
  • restartGame: Takes in new min and max values and generates a new secret number. Don’t forget to clear your old guesses!
  • printGuesses: Simply prints out all the guesses that have already been made.

Make sure you test your methods as you write them. It will be a lot harder to find any bugs if you try and test your code after writing everything. More code for your bugs to hide in! Once finish think about the following questions.

Questions to think about:

  1. Can you give a reason why it is important to make our secretNum field private? What can a user do if you have it set to public?
  2. Extra exercise: How would you write a second hint method that takes in a number and returns true if the secret number is divisible by that number?
  3. Did you use one method to generate the secret number in a specific range or did you repeat the same code in both your constructor and restartGame method?

 

Solutions: http://www.cse.unsw.edu.au/~tlen803/infs1609/

 

Assignment 1 Marks Available

Posted by on October 7th, 2013 · Announcements, Assignments

Marks for Assignment 1 are now available for collection. Go to the assignment management page: https://cgi.cse.unsw.edu.au/~give/Student/give.php, and select COMP1400. Then select “assignment1″ and press “Collect my Assignment”.

You will be presented with your assignment log. The log contains:

  • Your submitted code
  • Comments within the code
  • A summary of the tests and results
  • Output from incorrect tests
  • Your marks

Carefully read any comments that may have added to your log.

 

Week 10 Lab – Random Class

Posted by on October 4th, 2013 · Lab

Monday labs: Since Monday is a public holiday, the Monday groups should try to go to another lab just for this week.

These exercises are taken from Chapter 5 of the text book. You should also use this week to catch up with previous labs.

Exercise 5.14 Write some code (in BlueJ) to test the generation of random numbers. To do this, create a new class called RandomTester. You can create this class in a new project. In class RandomTester, implement two methods: printOneRandom (which prints out one random number) and printMultiRandom(int howMany) (which has a parameter to specify how many numbers you want, and then prints out the appropriate number of random numbers).

Exercise 5.15 Find the nextInt method in class Random that allows the target range of random numbers to be specified. What are the possible random numbers that are generated when you call this method with 100 as its parameter?

Exercise 5.16 Write a method in your RandomTester class called throwDice that returns a random number between 1 and 6 (inclusive).

Exercise 5.17 Write a method called getResponse that randomly returns one if the strings “yes”, “no”, or “maybe”.

Exercise 5.18 Extend your getResponse method so that it uses an ArrayList to store an arbitrary number of responses and randomly returns one of them. to Store

Exercise 5.19 Add a method to your RandomTester class that takes a parameter max and generates a random number in the range 1 to max (inclusive).

Exercise 5.20 Add a method to your RandomTester class that takes two parameters, min and max, and generates a random number in the range min to max (inclusive). Rewrite the body of the method you wrote for the previous exercise so that it now calls this new method to generate its result. Note that it should not be necessary to use a loop in this method.

Assignment 3 – Objects and ArrayLists

Posted by on October 4th, 2013 · Assignments

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

Due date: Midnight Friday 25 Oct (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.
  • 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 Jobjava
    Job.java Compiled Successfully
    Checking for JobQueue.java
    JobQueue.java Compiled Successfully

    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.

 

Classes are on this Week

Posted by on September 23rd, 2013 · Announcements

There has been some confusion about mid-semester break.

Please note that there are classes for COMP1400 and INFS1609 this week, and next week is mid-semester break.

Week 9 Lab – Classes and ArrayLists

Posted by on September 22nd, 2013 · Lab

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 a few different 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 int 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.

ArrayLists

  • Create a new class Course, that contains an ArrayList, called students, that stores all the students in a class. It should also have fields for the class id, like COMP1400 or INFS1609 and a String type for the course name.
  • Call the size method to check that the list is initially empty.
  • Call the add method to add some students 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. Test this on the ArrayList of students.

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