Chapter 4

Exercise 4.2
10
Exercise 4.3
item.get(4);
Exercise 4.4
14
Exercise 4.5
notes.add(meeting);
Exercise 4.6
dates.remove(2);
Exercise 4.7
5
Exercise 4.8
    public void removeNote(int noteNumber) {
if(noteNumber < 0) {
// This is not a valid note number, so do nothing.
}
else if(noteNumber < numberOfNotes()) {
// This is a valid note number, so we can remove it.
notes.remove(noteNumber);
}
else {
// This is not a valid note number, so do nothing.
}
}
Exercise 4.9
public void listAllNotes()

Exercise 4.10

No. We have no idea how many lines we would need.

Exercise 4.14

    public void showNote(int noteNumber)
{
if(noteNumber < 0) {
System.out.println("This is not a valid note number");
}
else if(noteNumber <= numberOfNotes()) {
// This is a valid note number, so we can print it.
System.out.println(notes.get(noteNumber));
}
else {
System.out.println("This is not a valid note number");
}
}

Exercise 4.15

    public void listNotes()
{
int index = 0;
while(index < notes.size()) {
System.out.println(index + ": " + notes.get(index));
index++;
}
}

Exercise 4.15

The value does not vary.

    public void listNotes()
{
int index = 0; int noteSize = notes.size();
while(index < noteSize) {
System.out.println(index + ": " + notes.get(index));
index++;
}
}
Exercise 4.17

/**
* Show a note.
* @param noteNumber The number of the note to be shown.
*/
public void showNote(int noteNumber)
{
if(noteNumber < 1) {
// This is not a valid note number, so do nothing.
}
else if(noteNumber <= numberOfNotes()) {
// This is a valid note number, so we can print it.
System.out.println(notes.get(noteNumber - 1));
}
else {
// This is not a valid note number, so do nothing.
}
}

/**
* List all notes in the notebook.
*/
public void listNotes() {
int index = 0;
while(index < notes.size()) {
System.out.println( (index + 1) + ": " + notes.get(index));
index++;
}
} /**
* Remove a note from the notebook if it exists.
* @param noteNumber The number of the note to be removed.
*/
public void removeNote(int noteNumber)
{
if(noteNumber < 1) {
// This is not a valid note number, so do nothing.
}
else if(noteNumber < numberOfNotes()) {
// This is a valid note number.
notes.remove(noteNumber-1);
}
else {
// This is not a valid note number, so do nothing.
}
}

Exercise 4.18

Loops are used to repeat some piece of code a number of times. If statements does not repeat anything.

Exercise 4.19-4.21

import java.util.ArrayList;

/**
* Store details of club memberships.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Club
{
// Define any necessary fields here ...
ArrayList members;
/**
* Constructor for objects of class Club
*/
public Club()
{
// Initialise any fields here ...
members = new ArrayList();
}
/**
* Add a new member to the club's list of members.
* @param member The member object to be added.
*/
public void join(Membership member)
{
members.add(member);
}
/**
* @return The number of members (Membership objects) in
* the club.
*/
public int numberOfMembers()
{
return members.size();
}
}

Exercise 4.22

There is a casting to Lot in this line:
Lot selectedLot = (Lot) lots.get(number-1);

Exercise 4.23

An error is printed:
incompatible types - found java.lang.Object but expected Lot

Exercise 4.24

    /**
* Closes the auction and prints out the details of the lots
*/
public void close(){
Iterator it = lots.iterator();
while(it.hasNext()) {
Lot lot = (Lot) it.next();
System.out.println(lot.getNumber() + ": " +
lot.getDescription());
// Include any details of a highest bid.
Bid highestBid = lot.getHighestBid();
if(highestBid != null) {
System.out.println(" Highest bidder: " +
highestBid.getBidder().getName());
System.out.println(" Bid: " +
highestBid.getValue());
}
else {
System.out.println(" Not sold");
}
}
}

Exercise 4.25

    /**
* Returns a list of unsold lots
*/
public ArrayList getUnsold() {
ArrayList unsoldLots = new ArrayList();
Iterator it = lots.iterator();
while(it.hasNext()) {
Lot lot = (Lot) it.next();
Bid highestBid = lot.getHighestBid();
if(highestBid == null) {
unsoldLots.add(lot);
}
}
return unsoldLots;
}

Exercise 4.26

If the method getLot is called with a lot-number that have been removed the following message is printed in the terminal window:
Internal error: Wrong lot returned. Number: 1

Exercise 4.27

    /**
* Return the lot with the given number. Return null
* if a lot with this number does not exist.
* @param number The number of the lot to return.
*/
public Lot getLot(int number)
{

Iterator it = lots.iterator();
while(it.hasNext()) {
Lot lot = (Lot) it.next();
if(lot.getNumber() == number) {
return lot;
} else if (lot.getNumber() > number) {
System.out.println("Lot number: " + number +
" does not exist.");
return null;
}
}
return null; //if there are no lots at all
}

Exercise 4.28

    /**
* Remove the lot with the given lot number.
* @param number The number of the lot to be removed
* @return The Lot with the given number, or null if
* there is no such lot.
*/
public Lot removeLot(int number) {
//First we find the lot with the given number
Lot lot = getLot(number);
if(lot != null) {
//Then we can use the method remove with lot as argument
lots.remove(lot);
}
return lot;
}

Exercise 4.29

The documentation for LinkedList can be found here: http://java.sun.com/j2se/1.4.2/docs/api/java/util/LinkedList.html

The LinkedList have these methods that ArrayList does not have:

void addFirst(Object o)
void addLast(Object o)
Object getFirst()
Object getLast()
ListIterator listIterator(int index)
Object removeFirst()
Object removeLast()

The ArrayList have these methods that LinkedList does not have:

void ensureCapacity(int minCapacity)
protected void removeRange(int fromIndex, int toIndex)
void trimToSize()

Exercise 4.30

    /**
* Determine the number of members who joined in the
* given month
* @param month The month we are interested in.
* @return The number of members.
*/
public int joinedInMonth(int month) {
if(month < 1 || month > 12) {
System.out.println("Month " + month + " out of range. Must be in the range 1 ... 12");
}
int count = 0;
Iterator it = members.iterator();
while(it.hasNext()) {
Membership member = (Membership) it.next();
if(member.getMonth() == month) {
count++;
}
}
return count;
}

Exercise 4.31

    public ArrayList purge(int month, int year) {
if(month < 1 || month > 12) {
System.out.println("Month " + month + " out of range. Must be in the range 1 ... 12");
}
ArrayList purged = new ArrayList();
Iterator it = members.iterator();
while(it.hasNext()) {
Membership member = (Membership) it.next();
if(member.getMonth() == month && member.getYear() == year) {
// Must use the remove method from the iterator.
// Check the documentation for the Iterator for more info.
it.remove();
purged.add(member);
}
}
return purged;
}

Exercise 4.32

    public void printProductDetails()
{
Iterator it = stock.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}

Exercise 4.33

    public Product findProduct(int id)
{
Iterator it = stock.iterator();
while(it.hasNext()) {
Product product = (Product) it.next();
if(product.getID() == id) {
return product;
}
}
return null;
}

Exercise 4.34

    public int numberInStock(int id)
{
Product product = findProduct(id);
if(product != null) {
return product.getQuantity();
}
else {
return 0;
}
}

Exercise 4.35

    public void delivery(int id, int amount)
{
Product product = findProduct(id);
if(product != null) {
product.increaseQuantity(amount);
}
}

Exercise 4.36


/**
* Print details of all the products which has stock
* levels below the given amount
*/
public void printLowStockProducts(int upperLimit)
{
Iterator it = stock.iterator();
while(it.hasNext()) {
Product product = (Product) it.next();
if(product.getQuantity() < upperLimit) {
System.out.println(product);
}
}
} /**
* Add a product to the list.
* @param item The item to be added.
*/
public void addProduct(Product item)
{
if( ! stock.contains(item)) {
stock.add(item);
}
} /**
* Try to find a product in the stock with the given name.
* @return The identified product, or null if there is none
* with a matching name.
*/
public Product findProduct(String name)
{
Iterator it = stock.iterator();
while(it.hasNext()) {
Product product = (Product) it.next();
if(product.getName().equals(name)) {
return product;
}
}
return null;
}

Exercise 4.37

The busiest time of day: 18

Exercise 4.38

Person[] person;

Exercise 4.39

boolean[] vacant;

Exercise 4.41

int[] counts;

boolean[] occupied = new boolean[5000];

Exercise 4.42

readings = new double[60];
urls = new String[90];
machines = new TicketMachine[5];

Exercise 4.43

None. It only creates an array to hold String objects.

Exercise 4.44

double[] prices = new double[50]

Exercise 4.45

It throws an ArrayIndexOutOfBoundsException: 24

Exercise 4.46

    /**
* Print the hourly counts.
* These should have been set with a prior
* call to analyzeHourlyData.
*/
public void printHourlyCounts()
{
System.out.println("Hr: Count");
int hour = 0;
while(hour<hourCounts.length) {
System.out.println(hour + ": " + hourCounts[hour]);
hour++;
}
}

Exercise 4.47

    public void printGreater(double[] marks, double mean) {
for(int index = 0; index < marks.length; index++) {
if(marks[index] > mean) {
System.out.println(marks[index]);
}
}
}

Exercise 4.48

    public void listNotes()
{
for(int index=0; index < notes.size(); index++) {
System.out.println(notes.get(index));
}
}

Exercise 4.49

    /**
* Return the number of accesses recorded in the log file
*/
public int numberOfAccesses() {
int total = 0;

// Add the value in each element of hourCounts to total.
for(int hour=0; hour < hourCounts.length; hour++) {
total = total + hourCounts[hour];
}

return total;
}

Exercise 4.51

    /**
* Return the busiest hour of day
*/
public int busiestHour() {
int busiestHour = 0;
for(int hour = 1; hour < hourCounts.length; hour++) {
if(hourCounts[hour] > hourCounts[busiestHour]) {
busiestHour = hour;
}
}
return busiestHour;
}

Exercise 4.52

    /**
* Return the quietest hour of day
*/
public int quietestHour() {
int quietestHour = 0;
for(int hour = 1; hour < hourCounts.length; hour++) {
if(hourCounts[hour] < hourCounts[quietestHour]) {
quietestHour = hour;
}
}
return quietestHour;
}

Exercise 4.53

In the above implementation, it is the first one that is found.

Exercise 4.54

    /**
* Return the two-hour period which is busiest.
*/
public int busiestTwoHourPeriod() {
int busiestPeriod = 0;
int busiestPeriodCount = 0;
for(int hour = 0; hour < hourCounts.length-1; hour++) {
int periodCount = hourCounts[hour] + hourCounts[hour+1];
if(periodCount > busiestPeriodCount) {
busiestPeriod = hour;
busiestPeriodCount = periodCount;
}
}
return busiestPeriod;
}

Exercise 4.55

Reasons for choosing a fixed size array could be:

  • Performance is slightly better.
  • Avoids casting objects to Student when retrieving objects from the array.

Reasons for keeping the dynamically sized list:

  • No need to keep track of the current number of students.
  • Good for future enhancements (for instance if we want to have a method to remove a student from the list).

Exercise 4.60

    public void listNotes()
{
int index = 0;
do{
if(!notes.isEmpty()) {
System.out.println(notes.get(index));
index++;
}
} while(index < notes.size());
}