COMP1400 – Programming for Designers

Class announcements for Programming for Designers

COMP1400 – Programming for Designers random header image

Week 9 Lab – Classes and ArrayLists

Posted by on September 22nd, 2014 · Lab

The self-test quiz for week9 can be found here.

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 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.

 

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.