qwertyuiopasdfghjklzxcvbnmqwert ... · when you open the bluej editor for a class, you will most...

42
qwertyuiopasdfghjklzxcvbnmqwert yuiopasdfghjklzxcvbnmqwertyuiop asdfghjklzxcvbnmqwertyuiopasdfg hjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbn mqwertyuiopasdfghjklzxcvbnmqwe rtyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdf ghjklzxcvbnmqwertyuiopasdfghjklz xcvbnmqwertyuiopasdfghjklzxcvbn mqwertyuiopasdfghjklzxcvbnmqwe rtyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdf ghjklzxcvbnmqwertyuiopasdfghjklz xcvbnmqwertyuiopasdfghjklzxcvbn mrtyuiopasdfghjklzxcvbnmqwertyu BlueJ Answers Objects First With Java Bas, Roos

Upload: ngomien

Post on 04-Nov-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

qwertyuiopasdfghjklzxcvbnmqwert

yuiopasdfghjklzxcvbnmqwertyuiop

asdfghjklzxcvbnmqwertyuiopasdfg

hjklzxcvbnmqwertyuiopasdfghjklzx

cvbnmqwertyuiopasdfghjklzxcvbn

mqwertyuiopasdfghjklzxcvbnmqwe

rtyuiopasdfghjklzxcvbnmqwertyuio

pasdfghjklzxcvbnmqwertyuiopasdf

ghjklzxcvbnmqwertyuiopasdfghjklz

xcvbnmqwertyuiopasdfghjklzxcvbn

mqwertyuiopasdfghjklzxcvbnmqwe

rtyuiopasdfghjklzxcvbnmqwertyuio

pasdfghjklzxcvbnmqwertyuiopasdf

ghjklzxcvbnmqwertyuiopasdfghjklz

xcvbnmqwertyuiopasdfghjklzxcvbn

mrtyuiopasdfghjklzxcvbnmqwertyu

BlueJ Answers

Objects First With Java

Bas, Roos

1

Table of contents:

CHAPTER 1 2

CHAPTER 2 7

CHAPTER 3 24

CHAPTER 4 39

2

Chapter 1

Exercise 1.1:

N/A

Exercise 1.2:

If you invoke moveDown 2 times, the circle will move downwards 2 times. If you invoke

moveDown 3 times, the circle will move downwards 3 times.

The first time you invoke makeInvisible, the circle becomes invisible. Invoking this method

again does nothing, because the circle is already invisible.

Exercise 1.3:

To move the circle 70 pixels to the left you must invoke the moveHorizontal method with -70

as the parameter.

Exercise 1.4:

N/A

Exercise 1.5:

If you try to use a color that is not supported, the circle turns black.

Exercise 1.6:

An error message is displayed and the object does not change its color.

Exercise 1.7 and 1.8:

N/A

Exercise 1.9:

There are many ways to produce the images presented in figure 1.8. All have in common that

objects first have to be created, and then modified using methods. However the order in which

the object are created and manipulated can be different.

House: People: Create 2 square objects. Create 1 triangle object. Create 1 circle object. Make all objects visible. Change the shape, color and position

of the squares to create the walls and window for the house.

Change the shape, color and position of the triangle to create the roof.

Change the size, color and position of the circle to create the sun.

Create 2 circle objects. Create 2 person objects. Make all objects visible. Change the size, color and position of

the circles to create the ground and sun.

Change the size and position of the persons to place them on the green circle.

3

Exercise 1.10, 1.11, 1.12 and 1.13:

N/A

Exercise 1.14:

The picture class’s draw method works by first creating 2 square, 1 triangle, and 1 circle objects.

Those objects are then altered by invoking the same methods we used in the previous

exercises. When all that is done, the draw method invokes the makeVisible method for all

objects to make the actual picture appear on the screen.

Exercise 1.15:

N/A

Exercise 1.16:

sun = new Circle(); sun.changeColor("blue"); sun.moveHorizontal(100); sun.moveVertical(-40); sun.changeSize(80); sun.makeVisible();

(Changes to the original code are highlighted in yellow.)

Exercise 1.17:

Example of a valid solution:

(…) private Square wall; private Square window; private Triangle roof; private Circle sun; private Circle sun2; (…) (…) sun2 = new Circle(); sun2.changeColor("yellow"); sun2.moveHorizontal(200); sun2.moveVertical(-20); sun2.changeSize(45); sun2.makeVisible(); (…)

(Changes to the original code are highlighted in yellow.)

4

Exercise 1.18:

Example of a valid solution:

(…) sun = new Circle(); sun.changeColor("yellow"); sun.moveHorizontal(100); sun.moveVertical(-40); sun.changeSize(80); sun.makeVisible(); sun.slowMoveVertical(300); (…)

(Changes to the original code are highlighted in yellow.)

Exercise 1.19:

Example of a valid solution:

(…) public void sunset() { sun.slowMoveVertical(300); } (…)

(Changes to the original code are highlighted in yellow.)

Exercise 1.20:

Example of a valid solution:

(…) private Square wall; private Square window; private Triangle roof; private Circle sun; private Person stickman; (…) (…) public void sunset() { sun.slowMoveVertical(300); stickman = new Person(); stickman.moveHorizontal(350); stickman.moveVertical(28); stickman.makeVisible(); stickman.slowMoveHorizontal(-320); } (…)

(Changes to the original code are highlighted in yellow.)

Exercise 1.21:

N/A

5

Exercise 1.22:

The getName method returns the name of the student.

Exercise 1.23:

N/A

Exercise 1.24:

The numberOfStudents method returns the number of students currently enrolled in the

LabClass.

Exercise 1.25, 1.26 and 1.27:

N/A

Exercise 1.28:

LabClass fields:

String instructor

String room

String timeAndDay

ArrayList students

int capacity

Exercise 1.29:

N/A

Exercise 1.30:

Check appendix B.

Exercise 1.31: Some values in this exercise can be ‘contained’ in multiple types. That means that the

following table is just an example of which data types can be used to contain these values.

Value: Type:

0 Integer

“Hello” String

101 Integer

-1 Integer

True Boolean

“33” String

3.1415 Double

6

Exercise 1.32:

When you open the BlueJ editor for a class, you will most likely find a list of fields in the

following format:

Scope Datatype name

Examples:

Private int capacity Private String room

If you want to create a field, you simply make a new entry to this starting with the word

private, the datatype and a name for the new field.

So adding a field called ‘name’ to a circle object would mean adding the following line to the

circle class:

Private String name

Exercise 1.33*: Void send(string iets) *The question does not specify a name for the parameters*

Exercise 1.34*:

int average (int parameter1, int parameter2) *The question does not specify a name for the parameters*

Exercise 1.35:

The book I am reading right now can be both an object and a class, depending on how you

look at it.

If the book is an object, it belongs to the ‘books’ class. Examples of other objects would be

different books e.g. Harry Potter, the Bible, the Da Vinci code etc.

If the book is a class, other object would be the different prints and/or editions of the book

that have been released e.g. Objects First with Java first edition, Objects First with Java second

edition etc.

Exercise 1.36:

An object can ‘have’ only a single class. The easiest way to explain this would to imagine a class

being a template for an object. A template can produce multiple objects, but an object cannot

have been created by more than one template.

7

Chapter 2

Exercise 2.1:

N/A

Exercise 2.2:

Printing a ticket always resets the balance to zero.

Exercise 2.3:

Strange things about the ticket machine's behavior:

The printTicket method doesn’t check if enough money has been inserted.

The printTicket method always resets the balance to zero, even if the amount of money

inserted is higher than the ticket price.

The insertMoney method accepts negative parameters

It is possible to create a ticket machine with a negative ticket price.

Exercise 2.4:

N/A

Exercise 2.5:

Yes. The ticket machine first checks what the cost of a ticket is, then prints that price on the

ticket itself.

Exercise 2.6:

Public class Student

Public class LabClass

Exercise 2.7: Yes, it matters whether we write:

public class Ticketmachine or class public Ticketmachine

When you make this change in BlueJ, the scope highlighting reflects the changes in the code,

making it apparent that BlueJ no longer ‘understands’ how the code structured.

The error message BlueJ displays when trying to compile is:

<identifier> expected.

Although the text of the error does not adequately explain what is wrong, the compiler does

point to the place where the error is located.

8

Exercise 2.8:

It is possible to leave out the word public from the outer wrapper of the TicketMachine class.

Exercise 2.9:

It is not possible to leave out the word class from the outer wrapper of the TicketMachine

class.

Exercise 2.10:

List of fields, constructors and methods in the TicketMachine class:

Fields:

price balance total

Constructors: TicketMachine

Methods: getPrice getBalance insertMoney printTicket

Exercise 2.11:

The constructor differs from the methods of a class in the following ways:

The name of the constructor is the same as the name of the class. (And therefore starts

with a capital letter!)

A constructor can never have a return type.

Exercise 2.12:

What do you think is the type of each of the following fields?

private int count; = Integer

private Student representative; = Student

private Server host; = Server

Exercise 2.13:

What are the names of the following fields?

private boolean alive; = alive

private Person tutor; = tutor

private Game game; = game

9

Exercise 2.14:

The following type names from exercise 2.12 and 2.13 are class names:

Student

Server

Person

Game

The reason these names are class names is because they are not any of the primitive types.

Another hint would be that they all begin with a capital letter, which is a naming convention

the book primarily uses for classes.

Exercise 2.15:

Yes, the order in which the words for a field declaration are written is very important. The code

will not work if the order is not correct.

Exercise 2.16:

Yes, it is always necessary to have a semicolon at the end of a field declaration.

Exercise 2.17:

private int status.

Exercise 2.18:

Constructor: public Student(String name)

Class: Student

Exercise 2.19:

Constructor: public Book(String title, double price)

Exercise 2.20: The Book class will most likely have a field containing a string, and a field containing a

double. You can assume that the fields will have a different name than the parameters, eg.,

‘label’ and ‘cost’ instead of ‘title’ and ‘price’.

Exercise 2.21:

Name = petsName

Exercise 2.22*:

public Date(String month, int day, int year) *The question does not specify a name for the parameters*

Exercise 2.23: The difference between the getBalance and getPrice method is that one returns the value for

the price field, and that the other returns the value for the balance field.

10

Exercise 2.24:

“How much money has been entered so far?”

Exercise 2.25:

The name of the return statement does not have to be changed when the name of the method

is altered.

Exercise 2.26:

/** * Returns the total amount of money collected by * this machine. */ public int getTotal() { return total; }

Exercise 2.27:

Missing return statement.

Exercise 2.28:

The getPrice method returns an integer, the printTicket method returns nothing.

Exercise 2.29:

Both the insertMoney and printTicket methods do not have return statements. This can be

seen by the word void in their headers.

The reason why these methods do not require return statements is because they don’t return

information to the ‘caller’ of the method.

The insertMoney method increases the value of another variable, but does not return its new

value.

The printTicket method prints some text to the terminal, but printing text is not the same as

‘returning’ text. Therefore the method ends when all text is printed, and no information is

‘returned’ to the caller.

Exercise 2.30:

N/A

Exercise 2.31:

The header for a constructor never has the word void in it.

11

Exercise 2.32:

/** * Changes the price of a ticket from this machine */ public void setPrice(int cost) { price = cost; }

Exercise 2.33:

/** * Increase score by the given number of points. */ public void increase(int points) { score = score + points; }

Exercise 2.34:

The increase method is a mutator, because it changes the state of its object.

Exercise 2.35:

/** * Reduce price by the given amount. */ public void discount(int amount) { price = price - amount; }

Exercise 2.36:

My cat has green eyes.

Exercise 2.37:

/** * Asks the customer to insert the correct amount of money. */ public void prompt() { System.out.println("Please insert the correct amount of money."); }

Exercise 2.38 and 2.39:

# price cents.

Exercise 2.40:

No, because both versions print a line without any variables.

12

Exercise 2.41:

/** * Prints the price of a ticket */ public void showPrice() { System.out.println("The price of a ticket is " + price + " cents"); }

Exercise 2.42:

The showPrice method will show different prices for the different ticket machines. The reason

for this is that the method returns the value of the price variable.

Exercise 2.43:

/** * Create a machine that issues tickets with a fixed price. */ public TicketMachine() { price = 1000; balance = 0; total = 0; }

BlueJ will not require the user to enter a price when creating a ticket-machine.

Exercise 2.44:

See previous exercise.

Exercise 2.45:

/** * Removes all money from the machine. */ public void empty() { total = 0; }

Exercise 2.46:

The balance never changes if an error message is printed. If the user enters the value zero as

the parameter for the insertMoney method, an error is displayed.

Exercise 2.47: Using the ‘greater-than or equal-to’ operator means that the insertMoney method now accepts

a value of zero.

13

Exercise 2.48:

/** * Receive an amount of money from a customer. * Check that the amount is sensible. */ public void insertMoney(int amount) { if (amount <= 0) { System.out.println("Use a positive amount rather than: " + amount); } else { balance = balance + amount; } }

Exercise 2.49:

That feature was the visibility of the object. It is okay to use a boolean for this feature, because

an object can be either visible or invisible.

Exercise 2.50:

The naive ticket-machine increases the total with the balance, then resets the balance to zero.

The better ticket-machine first checks if the balance field is equal or greater than the price

field. Then it increases the total field with the value in the price field, and reduces the balance

field by the same amount.

Exercise 2.51:

Yes, it is possible to remove the else part of the if-statement and still compile the program. If

you try to print a ticket without inserted money, the method stops.

Exercise 2.52: No. The balance field can never become a negative value because the method checks whether

the value in the balance field is high enough before it decides to lower it.

Exercise 2.53:

N/A

Exercise 2.54:

saving = price*discount;

Exercise 2.55:

mean = total/count;

14

Exercise 2.56:

if (price > budget){ System.out.println("Too expensive"); } else { System.out.println("Just right"); }

Exercise 2.57:

if (price > budget){ System.out.println("Too expensive, your budget is: " + budget); } else { System.out.println("Just right"); }

Exercise 2.58:

The code provided in the exercise will always return the value zero. This is because it first sets

the balance field to zero, and then returns that value.

You can test this behavior by trying to make the method return any other value.

Exercise 2.59:

If you try to compile the code given in this exercise, you will the following error:

Unreachable statement

That error means that there is code in the method that will never be executed. The reason for

that is because a method ‘stops’ the moment it encounters a return statement.

Exercise 2.60:

The version does compile, but won’t work properly. The reason for that has to do with the

scope of certain variables. The altered code stores the value that determines the ticket price in

a local variable. When the constructor finishes, that variable is deleted.

Exercise 2.61*:

/** * Empties the machine and returns the value before the reset */ public int emptyMachine() { int resetTotal = total; total = 0; return resetTotal; }

*Variable names may be different than your own.

15

Exercise 2.62:

/** * Print a ticket if enough money has been inserted, and * reduce the current balance by the ticket price. Print * an error message if more money is required. */ public void printTicket() { int amountLeftToPay = price - balance; if(amountLeftToPay <= 0) { // Simulate the printing of a ticket. System.out.println("##################"); System.out.println("# The BlueJ Line"); System.out.println("# Ticket"); System.out.println("# " + price + " cents."); System.out.println("##################"); System.out.println(); // Update the total collected with the price. total = total + price; // Reduce the balance by the prince. balance = balance - price; } else { System.out.println("You must insert at least: " + (amountLeftToPay) + " more cents."); } }

Exercise 2.63:

See Appendix A

Exercise 2.64:

Name: getCode()

Return type: String

Exercise 2.65:

Name: setCredits

Parameter name: creditValue

Parameter type: integer

Exercise 2.66:

public class Person { }

16

Exercise 2.67:

private String name;

private int age;

private String code;

private int credits;

Exercise 2.68:

public Module(String moduleCode) { code = modulecode; }

Exercise 2.69:

public Person(String myName, int myAge) { name = myName; age = myAge; }

Exercise 2.70:

The code in the exercise has a void return type. Because the code is supposed to return the

value of an integer, this should be int:

public int getAge() { return age; }

Exercise 2.71:

public String getName() { return name; }

Exercise 2.72

public void setAge(int myAge) { age = myAge; }

Exercise 2.73:

public void printDetails() { System.out.println("The name of this person is: " + name); }

17

Exercise 2.74:

student1: Student

name “Benjamin Jonson”

id “738321”

credits 0

Exercise 2.75:

Henr557

Exercise 2.76:

The getLoginName method returns the following error:

java.lang.StringIndexOutOfBoundsException: String index out of range: 4

This happens because the method tries to ‘read’ the fourth position of the “djb” string, which it

simply does not have.

Exercise 2.77:

/** * Create a new student with a given name and ID number. */ public Student(String fullName, String studentID) { if(fullName.length() < 4){ System.out.println("The given name is too short!"); } if(studentID.length() < 3){ System.out.println("The given id is too short!"); } name = fullName; id = studentID; credits = 0; }

18

Exercise 2.78:

There are a couple of ways this exercise can be solved. The answer shown below ‘contains’ all

the altered code in the getLoginName method.

public String getLoginName() { int loginNameLength = 4; int loginIdLength = 3; int actualNameLength = name.length(); int actualIdLength = id.length(); if(actualNameLength <=4) { loginNameLength = actualNameLength; } if(actualIdLength <=3) { loginIdLength = actualIdLength; } return name.substring(0,loginNameLength) + id.substring(0,loginIdLength); }

Exercise 2.79:

102 “catfish” “cat9” “12cat” “cat39” “f’” java.lang.StringIndexOutOfBoundsException: String index out of range: 8

Exercise 2.80: TicketMachine t1 = new TicketMachine(1000);

t1.getBalance() 0 (int)

t1.insertMoney(500);

t1.getBalance() 500 (int)

Exercise 2.81:

The TicketMachine t2 = t1; command copies the state of the t1 object, and uses that to create

a new TicketMachine object named t2.

Therefore a call to return the balance of t2 should also return 500.

Exercise 2.82:

I would have expected that increasing the balance of the t1 object would have no effect on the

t2 object. This does not seem to be the case though. It seems that calling the insertMoney

method on either object increases the balance field of both the t1 and t2 objects.

19

Exercise 2.83:

/** * Returns the name of the author */ public String getAuthor() { return author; } /** * Returns the title of the book */ public String getTitle() { return title; }

Exercise 2.84:

/** * Prints the name of the author */ public void printAuthor() { System.out.println(author); } /** * Prints the title of the book */ public void printTitle() { System.out.println(title); }

Exercise 2.85:

// The fields. private String author; private String title; private int pages;

// The constructor. /** * Set the author, title and pages fields when this object * is constructed. */ public Book(String bookAuthor, String bookTitle, int bookPages) { author = bookAuthor; title = bookTitle; pages = bookPages; }

20

Exercise 2.85 cont.

// The methods. /** * Returns the amount of pages */ public int getPages() { return pages; }

Exercise 2.86:

Yes, the Book objects are immutable. Because there are no methods that change any of the

field variables, the object’s state cannot change after its creation.

Exercise 2.87:

/** * Prints details of the author, title and pages. */ public void printDetails() { System.out.println("Title: " + title); System.out.println("Author: " + author); System.out.println("Pages: " + pages); }

Exercise 2.88:

// The fields. private String author; private String title; private int pages; private String refNumber

// The constructor. /** * Set the author, title and pages fields when this object * is constructed. Also initializes the refNumber field. */ public Book(String bookAuthor, String bookTitle, int bookPages) { author = bookAuthor; title = bookTitle; pages = bookPages; refNumber = ""; }

21

Exercise 2.88 cont.

// The methods /** * Sets the refNumber */ public void setRefNumber(String ref) { refNumber = ref; } /** * Returns the refNumber */ public String getRefNumber() { return refNumber; }

Exercise 2.99:

/** * Prints details of the author, title and pages. Also prints the * refnumber, if it is present. */ public void printDetails() { System.out.println("Title: " + title); System.out.println("Author: " + author); System.out.println("Pages: " + pages); if(refNumber.length() > 0){ System.out.println("Refnumber = " + refNumber); } else{ System.out.println("Refnumber = ZZZ"); } }

Exercise 2.90:

/** * Sets the refNumber */ public void setRefNumber(String ref) { if( ref.length() >= 3){ refNumber = ref; } else{ System.out.println("Refnumber must be atleast 3 characters!"); } }

22

Exercise 2.91: // The fields. private String author; private String title; private int pages; private String refNumber; private int borrowed;

// The methods /** * Increases the value of the borrow field by one. */ public void borrow() { borrowed += 1; } /** * Returns the value of the borrow field. */ public int getBorrowed() { return borrowed; } /** * Prints all known details of the book. */ public void printDetails() { System.out.println("Title: " + title); System.out.println("Author: " + author); System.out.println("Pages: " + pages); System.out.println("Borrowed: " + borrowed + "x"); if(refNumber.length() > 0){ System.out.println("Refnumber = " + refNumber); } else{ System.out.println("Refnumber = ZZZ"); } }

Exercise 2.92: // The fields. private String author; private String title; private int pages; private String refNumber; private int borrowed; private boolean courseText;

23

Exercise 2.92 cont.

// The methods. /** * Set the author, title and pages fields when this object * is constructed. Also initializes the refNumber field. */ public Book(String bookAuthor, String bookTitle, int bookPages, boolean bookCourseText) { author = bookAuthor; title = bookTitle; pages = bookPages; refNumber = ""; courseText = bookCourseText; }

/** * Checks if a book is used as a course text book. */ public boolean isCourseText(){ return courseText; }

Exercise 2.93:

See appendix B

24

Chapter 3

Exercise 3.1:

Object diagram:

Class diagram:

25

Exercise 3.2:

Class diagrams change only when editing the source code of a project.

Exercise 3.3:

Object diagrams can change during execution of a program, when objects are created or

destroyed.

Exercise 3.4:

private Instructor tutor;

Exercise 3.5:

hours.increment();

Exercise 3.6:

minutes.increment();

Because the program gives no feedback when the rollover limit is reached, I need to check this

myself. The order I would do this in is as follows:

Check if the next increment would lead to a minute rollover.

If that is not the case, increase minutes by 1

If it is the case, rollover the minute display, and call increment on the hours object.

Exercise 3.7:

N/A

Exercise 3.8:

Error: non-static method getValue() cannot be referenced from a static context

Exercise 3.9:

nd.setValue(int 5);

Error: '.class' expected

nd.setValue(5);

Exercise 3.10:

If the setValue method is called with an illegal value, nothing happens. That is not a good

solution. Yes.

Exercise 3.11:

The method won’t accept a value of zero as the parameter.

Exercise 3.12:

The method will accept the parameter even if just one the conditions is met.

26

Exercise 3.13:

! (4 < 5) false

! false true

(2 > 2) || ((4 == 4) && (1 < 0)) false

(2 > 2) || (4 == 4) && (1 < 0) false

(34 != 33) && ! false true

Exercise 3.14:

(a && b || !a && !b)

Exercise 3.15:

(a &&!b || !a&&b)

Exercise 3.16:

a = b

Exercise 3.17:

The getDisplayValue methods ‘works’ in all circumstances, but it has no limits in place to make

sure it can only display a 2 digit number.

Exercise 3.18:

No. As long as one of the operands is a string, the end result will be a string.

Exercise 3.19:

9+3+”cat”=”12cat” “cat”+3+9=”cat39”

I’m not sure if this is correct, but I think the difference between statements is because a

statement is ‘parsed’ from left to right:

9 + 3 = 12. “cat” + 3 = “cat3”

12+”cat” = “12cat” “cat3” + 9 = “cat39”

Exercise 3.20:

The module operator is the remainder of an integer division. You can find this remainder by

checking how many times the right number ‘fits’ in the left. The number that remains is the

remainder of the division e.g.

11 % 2 = 1 (2 can ‘fit’ 5 times in 11, leaving a remainder of 1)

37 % 10 = 7 (10 can ‘fit’ 3 times in 37, leaving a remainder of 7)

34 % 4 = 2 (4 can ‘fit’ 8 times in 34, leaving a remainder of 2)

27

Exercise 3.20 cont.

The only case where this method does not work is when the first number is smaller than the

second. However those cases are even easier because the remainder is always the same as the

smallest number e.g.

3 % 5 = 3 (5 can ‘fit’ zero times in 3, leaving a remainder of 3)

14 % 33 = 14 (33 can ‘fit’ zero times in 14, leaving a remainder of 14)

10 % 21 = 10 (21 can ‘fit’ zero times in 10, leaving a remainder of 10)

Exercise 3.21:

8 % 3 = 2

Exercise 3.22:

Results of testing with negative numbers:

8 % 3 = 2 3 % 8 = 3

-8 % 3 = -2 -3 % 8 = -3

8 % -3 = 2 3 % -8 = 3

-8 % -3 = -2 -3 % -8 = -3

These results show rules we can use in the future:

If both numbers are positive, the result is also positive.

If only the first number is a negative, the result will be negative.

If only the second number is a negative, the result will be positive.

If both number are negative, the result is also negative

Exercise 3.23:

0, 1, 2, 3, 4

Exercise 3.24:

The amount of possible results for n % m is 2.147.483.646 Or simply put, 1 less than the amount

of different values a positive integer can hold.

Exercise 3.25:

The increment method uses the modulo operator to set the NumberDisplay value to zero if it

has reached the limit. We can easily observe this behavior by writing out the state of a

NumberDisplay object.

For our example we will set the current value to 1, and the rollover limit to 5.

28

limit = 5 value = 1

NumberDisplay1

(value+1) % limit = 2

2 % 5 = 2

limit = 5 value = 2

NumberDisplay1

(value+1) % limit = 2

3 % 5 = 3

limit = 5 value = 3

NumberDisplay1

(value+1) % limit = 2

4 % 5 = 4

limit = 5 value = 4

NumberDisplay1

(value+1) % limit = 2

5 % 5 = 0

limit = 5 value = 0

NumberDisplay1

Exercise 3.25 cont.

29

Exercise 3.26:

/** * Alternative increment method without using the modulo operator */ public void increment2() { value++; if (value == limit){ value = 0; } }

I have no idea about which method is ‘better’. I personally find the if-statement easier to read,

although I could imagine the modulo-statement using less computational resources.

Exercise 3.27:

Initial time = “00:00”

The reason the clock is set to this time is because it’s time has not been changed yet. Each

NumberDisplay object created its own ‘value’ field and set its value to zero. The extra zeros are

added by the getDisplayValue method.

Exercise 3.28:

N/A.

Exercise 3.29:

60x

Exercise 3.30:

private Rectangle window window = new Rectangle(2,2);

Exercise 3.31:

The second constructor also creates 2 NumberDisplay object with 24 and 60 as their rollover

limits. It then calls the setTime method, which calls the NumberDisplay’s setValue methods

to change their value.

Exercise 3.32:

The reason the second constructor does not call the updateDisplay method is because the

setTime method already does this. The constructors are the same, except for the call to the

setTime method.

Exercise 3.33:

p1.print(Naamloos, false); p1.getStatus(5)

30

Exercise 3.34:

No objects are created by the constructor of the picture class. Book is wrong.

Exercise 3.35:

roof.changeSize(60, 180); roof.moveHorizontal(20); roof.moveVertical(-60); roof.makeVisible();

Exercise 3.36:

No, the picture class does not contain internal method calls.

Exercise 3.37:

/** * Draw this picture. */ public void draw() { wall = new Square(); wall.moveHorizontal(-140); wall.moveVertical(20); wall.changeSize(120); wall.makeVisible(); window = new Square(); window.moveHorizontal(-120); window.moveVertical(40); window.changeSize(40); window.makeVisible(); roof = new Triangle(); roof.changeSize(60, 180); roof.moveHorizontal(20); roof.moveVertical(-60); roof.makeVisible(); sun = new Circle(); sun.moveHorizontal(100); sun.moveVertical(-40); sun.changeSize(80); sun.makeVisible(); setColor(); }

31

ClockDisplay

NumberDisplay

NumberDisplay12h

Exercise 3.38

The way I solved this exercise is by creating a second class called NumberDisplay12h. This

gives us the following class diagram:

The code for the NumberDisplay class is not altered. The code for the other classes can be

found in Appendix C.

Exercise 3.39: The answer to the previous exercise demonstrates the ‘store hour values 1 to 12’ solution. The

‘internal 12h clock’ solution I’ve come up also creates a second class called

NumberDisplay12h, but instead of just storing the values 1 to 12, it subtracts 12 if the value

field is greater than 12.

This means that if the clock is set to 16:23, the NumberDisplay12h class that provides the ‘hour’

part of the clock automatically subtracts 12 from 16, leaving 04:23

public String getDisplayValue() { if (value > 12){ value = value - 12; } if (value < 10) { return "0" + value; } else { return "" + value; } }

32

Exercise 3.40:

public class Tree { private Triangle leaves; private Square trunk; /** * Constructor for objects of class Picture */ public Tree() { leaves = new Triangle(); trunk = new Square(); }

Exercise 3.41:

public class Tree { private Triangle leaves; private Square trunk; /** * Constructor for objects of class Picture */ public Tree() { leaves = new Triangle(); trunk = new Square(); setup(); } /** * Draw this picture. */ public void setup() { trunk.moveHorizontal(-80); trunk.moveVertical(80); trunk.changeSize(40); trunk.changeColor("brown"); //custom color added to canvas class trunk.makeVisible(); leaves.moveHorizontal(38); leaves.moveVertical(-100); leaves.changeSize(180,150); leaves.changeColor("green"); leaves.makeVisible(); } }

33

Exercise 3.42:

N/A

Exercise 3.43:

Exercise 3.44, 3.45 and 3.46:

N/A

Exercise 3.47:

I would predict the next line marked is line 43, because that’s where the next code that will be

executed is placed.

My prediction was right, the debugger marked, but not executed the code on line 43. The

reason it skipped lines is because the if(item == null) statement was false.

Exercise 3.48:

When the printNextMailItem method is called a second time, there are no new messages to

print, which means the debugger will take the ‘other’ path at the if(item == null) statement.

Exercise 3.49: When I pressed the Step into button, the debugger showed me the code execution in the

print() method. The terminal then showed the ‘From’, ‘To’, and ‘Message’ appear one by one.

:testServer

MailServer

:mailClie1;

MailClient

server

user “Bas”

:mailClie2;

MailClient

server

user “Nel”

:mailClie3;

MailClient

server

user “Job”

34

Exercise 3.50:

N/A.

Exercise 3.51:

When a MailClient object invokes the sendMailItem method, a new MailItem object is

created with to, from and message parameters. When that is done, it invokes the post

method from the MailServer object.

Object diagram after invoking sendMailItem:

Exercise 3.52:

N/A.

Exercise 3.53:

N/A.

35

Exercise 3.54:

public class MailItem { // The sender of the item. private String from; // The intended recipient. private String to; // The text of the message. private String message; // The subject of the message. private String subject; public MailItem(String from, String to, String message, String subject) { this.from = from; this.to = to; this.message = message; this.subject = subject; } public String getFrom() { return from; } public String getTo() { return to; } public String getMessage() { return message; } public void print() { System.out.println("From: " + from); System.out.println("To: " + to); System.out.println("Message: " + message); System.out.println("Subject: " + subject); } }

(Changes to the original code are highlighted in yellow.)

36

public class MailClient { private MailServer server; private String user; public MailClient(MailServer server, String user) { this.server = server; this.user = user; } public MailItem getNextMailItem() { return server.getNextMailItem(user); } public void printNextMailItem() { MailItem item = server.getNextMailItem(user); if(item == null) { System.out.println("No new mail."); } else { item.print(); } } public void sendMailItem(String to, String message, String subject) { MailItem item = new MailItem(user, to, message, subject); server.post(item); } }

(Changes to the original code are highlighted in yellow.)

Exercise 3.55:

Screen display1 = new Screen(); if (numberOfPixels() > 2000000) { screen(false); //True would also be correct. }

Exercise 3.56:

Field to contain the NumberDisplay object for the seconds.

Both constructors need another line to create the NumberDisplay objects.

timeTick() has to be changed to increment seconds instead of minutes.

setTime() has to be altered to allow the setting of the seconds.

updateDisplay() needs another string to store the seconds in.

37

Exercise 3.57:

public class ClockDisplay { private NumberDisplay hours; private NumberDisplay minutes; private NumberDisplay seconds; private String displayString; // simulates the actual display public ClockDisplay() { hours = new NumberDisplay(24); minutes = new NumberDisplay(60); seconds = new NumberDisplay(60); updateDisplay(); } public ClockDisplay(int hour, int minute, int second) { hours = new NumberDisplay(24); minutes = new NumberDisplay(60); seconds = new NumberDisplay(60); setTime(hour, minute, second); } public void timeTick() { seconds.increment(); if(seconds.getValue() == 0) { // it just rolled over! minutes.increment(); { if(minutes.getValue() == 0) hours.increment(); } } updateDisplay(); } public void setTime(int hour, int minute, int second) { hours.setValue(hour); minutes.setValue(minute); seconds.setValue(second); updateDisplay(); } public String getTime() { return displayString; }

38

Exercise 3.57 cont.

private void updateDisplay() { displayString = hours.getDisplayValue() + ":" + minutes.getDisplayValue() + ":" + seconds.getDisplayValue(); } }

(Changes to the original code are highlighted in yellow.)

Exercise 3.58:

The design of the ClockDisplay class can support any number of fractions of seconds. The

resulting code would not be very readable, but in theory it can be done.

Example of timeTick() with hundredths of a second:

/** * This method should get called 100 times per second - it makes * the clock display progress with 100th of a second. */ public void timeTick() { hundredthseconds.increment(); if(hundredthseconds.getValue() == 0){ tenthseconds.increment(); if(tenthseconds.getValue() == 0) { seconds.increment(); if(seconds.getValue() == 0) { // it just rolled over! minutes.increment(); { if(minutes.getValue() == 0) hours.increment(); } } updateDisplay(); } } }

Exercise 3.59:

Saving this for later.

39

Chapter 4

Exercise 4.1:

The number of files returned by numberOfFiles matches the number I stored.

Exercise 4.2:

I did not get an error, I did somewhat expect to get an error.

Exercise 4.3: After deleting the file at position 0, the file at position 1 moved to position 0. That means that

calling listFile(0) returned the second file I added.

Exercise 4.4:

private ArrayList<Book> library;

Exercise 4.5:

cs101 = new ArrayList<Student>();

Exercise 4.6:

private ArrayList<MusicTrack> tracks;

Exercise 4.7:

library = new ArrayList<Book>();

library = new ArrayList<>();

cs101 = new ArrayList<Student>();

cs101 = new ArrayList<>();

tracks = new ArrayList<MusicTrack>();

tracks = new ArrayList<>();

Exercise 4.8:

10.

Exercise 4.9:

items.get(4)

Exercise 4.10:

14.

Exercise 4.11:

files.add(favoriteTrack);

40

Exercise 4.12:

dates.remove(2);

Exercise 4.13:

5.

Exercise 4.14:

/** * Checks to see if a particular index value is valid. * @param index The index integer to check. */ public void checkIndex(int index) { if(index < 0 || index >= files.size()) { if(files.size() == 0){ System.out.println("The collection is empty!"); } else{ System.out.println("Index is not valid!"); System.out.println("Valid index is 0 to " + (files.size()-1)); } } }

Exercise 4.15:

/** * Checks to see if a particular index value is valid. * @param index The index integer to check. */ public void checkIndex(int index) { if(index < 0 || index >= files.size()) { if (files.size() == 0){ System.out.println("The collection is empty!"); } else{ System.out.println("Index is not valid!"); System.out.println("Valid index is 0 to " + (files.size()-1)); } } }

41

Exercise 4.16:

/** * List a file from the collection. * @param index The index of the file to be listed. */ public void listFile(int index) { if (validIndex(index) == true) { String filename = files.get(index); System.out.println(filename); } } /** * Remove a file from the collection. * @param index The index of the file to be removed. */ public void removeFile(int index) { if (validIndex(index) == true) { files.remove(index); } }