0% found this document useful (1 vote)
3K views

Chapter 4 Solutions Object First With Java

The document contains code snippets and exercises from Chapter 4 of an unknown textbook. It includes code for array lists, loops, methods, conditionals, and other basic programming concepts. The exercises range from simple code examples to more complex tasks like searching arrays, removing items, and manipulating objects.

Uploaded by

Vivian Vy Lê
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
3K views

Chapter 4 Solutions Object First With Java

The document contains code snippets and exercises from Chapter 4 of an unknown textbook. It includes code for array lists, loops, methods, conditionals, and other basic programming concepts. The exercises range from simple code examples to more complex tasks like searching arrays, removing items, and manipulating objects.

Uploaded by

Vivian Vy Lê
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 11

Exercise 4.

private ArrayList<Book> library;

Exercise 4.3

10

Exercise 4.4

item.get(4);

Exercise 4.5

14

Exercise 4.6

notes.add(meeting);

Exercise 4.7

dates.remove(2);

Exercise 4.8

Exercise 4.9

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

public void listAllNotes()

Exercise 4.11

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


Exercise 4.15

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

public void test() { int i = 10;


while(i <= 95) {
System.out.println(i);
i = i + 5;
}}

Exercise 4.17

public void sum(int a, int b) {


int number = a + 1;
int sum = 0;
while(number < b) {
sum = sum + number;
number = number + 1;
}
System.out.println(sum);
}

Exercise 4.18

public boolean isPrime(int n) {


int divisor = 2;
while(divisor < n ) {
if(n % divisor != 0) {
return false;
}
divisor = divisor + 1;
}
return true;
}

Exercise 4.19

public boolean search(String searchString) {


int index = 0;
boolean found = false;
while(index < notes.size() && !found) {
String note = notes.get(index);
if(note.contains(searchString)) {
found = true;
}
else {
index++;
}
}
if(found) {
System.out.println("Found search term in note: " +
notes.get(index));
} else {
System.out.println("Search term not found.");
}
}
Exercise 4.20

public void listNotes()


{
int index = 0;
for(String note : notes) {
System.out.println(index + ": " + note);
index++;
}
}

Exercise 4.21

The value does not vary.

public boolean search(String searchString) {


int index = 0;
boolean found = false; int size = notes.size();
while(index < size && !found) {
String note = notes.get(index);
if(note.contains(searchString)) {
found = true;
}
else {
index++;
}
}
if(found) {
System.out.println("Found search term in note: " +
notes.get(index));
} else {
System.out.println("Search term not found.");
}
}

Exercise 4.22

/**
* 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;
for(String note : notes) {
System.out.println((index + 1) + ": " + note);
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.23-4.25

import java.util.ArrayList;
/**
* Store details of club memberships.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Club
{
ArrayList<Membership> members;
/**
* Constructor for objects of class Club
*/
public Club()
{
members = new ArrayList<Membership>();
}
/**
* 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.26
public void close(){
for(Lot lot : lots) {
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.27

/**
* Returns a list of unsold lots
*/
public ArrayList<Lot> getUnsold() {
ArrayList<Lot> unsoldLots = new ArrayList<Lot>();
for(Lot lot : lots) {
Bid highestBid = lot.getHighestBid();
if(highestBid == null) {
unsoldLots.add(lot);
}
}
return unsoldLots;
}

Exercise 4.28

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

/**
* 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)
{
for(Lot lot : lots) {
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.30

/**
* 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.31

The documentation for LinkedList can be found here:


http://java.sun.com/j2se/1.5.0/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.32

/**
* 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;
while(Membership member : members) {
if(member.getMonth() == month) {
count++;
}
}
return count;
}

Exercise 4.33

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<Membership> purged = new ArrayList<Membership>();
Iterator<Membership> it = members.iterator();
while(it.hasNext()) {
Membership member = 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.34

public void printProductDetails()


{
for(Product product : stock) {
System.out.println(product);
}
}

Exercise 4.35

public Product findProduct(int id)


{
for(Product product : stock) {
if(product.getID() == id) {
return product;
}
}
return null;
}

Exercise 4.36

public int numberInStock(int id)


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

Exercise 4.37

public void delivery(int id, int amount)


{
Product product = findProduct(id);
if(product != null) {
product.increaseQuantity(amount);
}
}

Exercise 4.38

/**
* Print details of all the products which has stock
* levels below the given amount
*/
public void printLowStockProducts(int upperLimit)
{
for(Product product : stock) {
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)
{
for(Product product : stock) {
if(product.getName().equals(name)) {
return product;
}
}
return null;
}

Exercise 4.39

The busiest time of day: 18


Exercise 4.40

Person[] person;
Exercise 4.41

boolean[] vacant;
Exercise 4.43

int[] counts;

boolean[] occupied = new boolean[5000];


Exercise 4.44

readings = new double[60];


urls = new String[90];
machines = new TicketMachine[5];
Exercise 4.45

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


Exercise 4.46

double[] prices = new double[50]


Exercise 4.47

It throws an ArrayIndexOutOfBoundsException: 24
Exercise 4.48

/**
* 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.49

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

public void listNotes()


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

Exercise 4.51

public void listNotes()


{
for(String note : notes) {
System.out.println(note);
}
}

Exercise 4.52

/**
* 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 hourCount : hourCounts) {
total = total + hourCount;
}
return total;
}

Exercise 4.54

/**
* 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.55

/**
* 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.56
In the above implementation, it is the first one that is found.
Exercise 4.57

/**
* 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.58

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());
}

You might also like