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.

No Comments so far ↓

There are no comments yet...Kick things off by filling out the form below.

You must log in to post a comment.