Monday, August 30, 2010

Chapter 2 Questions


2.1

Create a TicketMachine object on the object bench and take a look at its methods. You should see the following: getBalance(), getPrice(), insertMoney(), and printTicket(). Try out the getPrice() method. You should see a return value containing the price of the tickets that was set when this object was created. Use the insertMoney() method to simulate inserting an amount of money into the machine and then use getBalance() to check that the machine has a record of the amount inserted. You can insert several separate amounts of money into the machine, just like you might insert muliple coins or notes into a real machine. Try inserting the exact amount required for a ticket. As this is a simple machine, a ticket will not be issued automatically, so once you have inserted enough money, call the printTicket() method. A facsimile ticket should be printed in the BlueJ terminal window.

Okay, Completed.

2.2

What value is returned if you check the machine's balance after it has printed a ticket?

Zero.

2.3

Experiment with inserting different amounts of money before printing tickets. Do you notice anything strange about the machine's behavior?

What happens if you insert too much money into the machine - do you receive any refund?

What happens if you do not insert enough and then try to print a ticket?

If you insert too much money into the machine, it takes it all. And if you do not insert enough and then try to print a ticket, it still prints out the ticket.




2.4

Try to obtain a good understanding of a ticket machine's behavior by interacting with it on the object bench before we start looking at how the TicketMachine class is implemented in the next section.

Okay, Completed.

2.5

Create another ticket machine for tickets of a different price. Buy a ticket from that machine.

Does the printed ticket look different?

The price is different.

2.6

Write out what you think the outer layers of the Student and LabClass classes might look like - do not worry about the inner part.

The out layers of the Student:

public class Student { }


The out layers of the LabClass:

public class LabClass { }

2.7

Does it matter whether we write

public class TicketMachine

or

class public TicketMachine

in the outer wrapper of a class?

Edit the source of the TicketMachine class to make the change and then close the editor window.

Do you notice a change in the class diagram?

What error message do you get when you now press the compile button?

Do you think this message clearly explains what is wrong?

Yes. The order of the terms: ‘public’ and ‘class’ matter.

2.8

Check whether or not it is possible to leave out the word public from the outer wrapper of the TicketMachine class.

It is possible.

2.9

From your earlier experimentation with the ticket machine objects within BlueJ you can probably remember the names of some of the methods - printTicket() for instance. Look at the class definition in code 2.1 and use this knowledge, along with additional information about ordering we have given you, to try to make a list of the names of the fields, constructors, and methods in the TicketMachine class.

Hint: There is only one constructor in the class.

Fields:

price

balance

total


Constructors:

TicketMachine


Methods:

getPrice

getBalance

insertMoney

printTicket




2.10

Do you notice any features of the constructor that makes it significantly different from the other methods of the class?

There is no return type and the constructor name is the same.

2.11

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

private int count

private Student representative

private Server host

int

Student

Server

2.12

What are the names of the following fields?

private boolean alive

private Person tutor

private Server host

alive

tutor

game

2.13

In the following declaration from the TicketMachine class

private int price;

does it matter which order the three words appear in ?

Edit the TicketMachine class to try different orderings. After each change, close the editor.

Does the appearance of the class diagram after each change give you a clue as to whether or not the other orderings are possible?

Check by pressing on the compile button to see if there is an error message.

Make sure that you reinstate the original version after your experiments.

Yes, the order matters.

2.14

Is it always necessary to have a semicolon at the end of a field declaration? Once again experiment via the editor. The rule you will learn here is important, be sure to remember it.

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

2.15

Write in the full declaration for a field of type int whose name is status.

private int status;

2.16

To what class does the following constructor belong?

public Student (String name)

class Student

2.17

How many parameters does the following constructor have and what are their types?

public Book(String title, double price)

2

2.18

Can you guess what types some of the Book class's fields might be?

Can you assume anything about the names of its fields?

Sting and double


No.

2.19

Supose that the class Pet has a field called name that is of type String. Write an assignment in the body of the following constructor so that the name field will be initialized with the value of the constructor's parameter.

public Pet (String petsName)

{

>>

}

name = petsName;

2.20

What is wrong with the following constructor of TicketMachine?

public TicketMachine (int ticketCost)

{

int price = ticketCost;

balance = 0;

total = 0;

}

Once you have spotted the problem, try out this version in the naive-ticket-machine project.

Does this version compile?

Create an object, and then inspect its fields. Do you notice something wrong about the value of the price fiield in the inspector with this version?

Can you explain why this is?

The price variable is declared in the constructor.

2.21

Compare the getBalance() method with the getPrice() method.

What are the differences between them?

The getPrice() returns the price and getBalance() returns the balance.

2.22

If a call to getPrice() can be characterized as "What do tickets cost?", how would you characterize a call to getBalance()?

How much money do I have in the machine.

2.23

If the name of getBalance() is changed to getAmount(), does the return statement in the body of the method need to be changed too?

Try it out within BlueJ.

No

2.24

Define an accessor method, getTotal(), that returns the value of the total field.

public int getTotal() { return total; }

2.25

Try removing the return statement from the body of getPrice().

What error message do you get when you try compiling the class?

Missing return statement.

2.26

Compare the method signatures of getPrice() and printTicket() in code 2.1.

Apart from their names, what is the main difference between them?

The signature for printTicket() has void as return type and the signature for getPrice() has an int as return type.

2.27

How can we tell from just its header that setPrice() is a method and not a constructor?

public void setPrice(int ticketCost)

No.

2.29

How can we tell from just its header that setPrice() is a method and not a constructor?

public void setPrice(int ticketCost)

It has a return type (void) and constructors do not have return types.

2.30

Complete the body of the setPrice() method so that it assigns the value of its parameter to the price field.

price = ticketPrice;

2.31

Complete the body of the following method, whose purpose is to add the value of its parameter to a field named score.

public void increase (int points)

score = score + points;

2.32

Can you compile the following method, whose purpose is to subtract the value of its parameter from a field named price?

public void discount (int amount)

price = price - amount;

2.33

Add a method called prompt() to the TicketMachine class. This should have a void return type and take no parameters. The body of the method should print something like:


"Please insert the correct amount of money."

public void prompt () { System.out.println (“Please insert the amount of money.”); }

2.34

Add a showPrice() method to the TicketMachine class. This should have a void return type and take no parameters. The body of the method should print something like:

"The price of a ticket is xyz cents"

where xyz should be replaced by the value held in the price field when the method is called.

public void showPrice () { System.out.println (“The price of the ticket is “” + price + “” cents”); }


2.35

Create two ticket machines with differently priced tickets.

Do calls to their showPrice() methods show the same output or different?

How do you explain this effect?

Different. Becuase each ticketmachine object has its own price.

2.36

What do you think would be printed if you altered the fourth statement of printTicket() so that the price also has quotes around it as follows?

System.out.println("# " + "price" + " cents.");

Instead of printing out the actual price of the ticket, it displays “price”.


2.37

What about the following version?

System.out.println ("# price cents.");

It prints out “price”.

2.38

Could either of the previous two versions be used to show the price of tickets in different ticket machines?

Explain your answer.

No. Because there is no specific price displayed.

2.39

Modify the constructor of TicketMachine so that it no longer has a parameter. Instead, the price of tickets should be fixed at 1000 cents.

What effect does this have when you construct ticket machine objects within BlueJ.

public TicketMachine() { price = 1000; balance = 0; total = 0; }

2.40

Implement a method, empty(), that simulates the effect of removing all money from the machine. This method should have a void return type, and its body should simply set the total field to zero.

Does this method need to take any parameters?

Test your method by creating a machine, inserting some money, printing some tickets, checking the total then emptying the machine.

Is this method a mutator or an accessor?

public void empty() { total = 0; }

2.41

Implement a method setPrice(), that is able to set the price of tickets to a new value. The new price is passed in as a parameter value to the method.

Test your method by creating a machine, showing the price of tickets, changing the price, and then showing the new price.

Is this method a mutator? Explain.

public void setPrice(int newPrice) { price = newPrice; }

2.42

Give the class two constructors. One should take a single parameter that specifies the price, and the other should take no parameter and set the price to a default value of your choosing.

Test your implementation by creating machines via the two different constuctors.

public TicketMachine() { price = 1000; balance = 0; total = 0; }

2.43

Check that the behavior we have discussed here is accurate by creating a TicketMachine instance and calling insertMoney() with various actual parameter values.

Check the balance both before and after calling insertMoney().

Does the balance ever change in the cases when an error message is printed?

Try to predict what will happen if you enter the value zero as the parameter, and then see if you are right.

The balance does not change when an error message is printed.
Inserting 0, results in an error message.

2.44

Predict what you think will happen if you change the test in insertMoney() to use the greater-than or equal-to operator.

if (amount>=0)

Check your predictions by running some tests. What difference does it make to the behavior of the method?

It does not print an error message.
It does not change the behavior of the method.

2.45

In the shapes project we looked at in chapter 1 we used a boolean field to control a feature of the circle objects.

What was that feature?

Was it well suited to being controlled by a type with only two different values?

The field is: isVisible

It determines whether the circle was visible or invisible.

Yes. As circle is either visible or not, only two states are needed.

2.46

In this version of printTicket() we also do something slightly different with the total and balance fields.

Compare the implementation of the method in Code 2.1 with that in code 2.8 to see whether you can tell what those differences are.

Then check your understanding by experimenting within BlueJ.


In the printTicket method of Code 2.8 the total is increased with the price of the ticket, and not the balance.
The balance is then decreased with the price.

2.47

After a ticket has been printed, could the value in the balance field ever be set to a negative value by subtracting price from it?

Justify your answer.

Okay, Completed.

2.48

So far we have introduced you to two arithmetic operators, + and -, that can be used in arithmetic expressions in Java. Take a look at Appendix D to find out what other operators are available.

Okay, Completed.

2.49

Write an assignment statement that will store the result of multiplying two variables, price and discount, into a third variable, saving.

saving = price x discount;

2.50

Write an assignment statement that will divide the value in total by the value in count and store the result in mean.

mean = total / count;

2.51

Write an if statement that will compare the value in price against the value in budget.

If price is greater than budget then print the message..

"too expensive"

otherwise print the message..

"just right".

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

2.52

Modify your answer to the previous exercise so that the message if the price is too high includes the value of your budget.

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

2.53

Why does the following version of refundBalance() not give the same results as the original?

public int refundBalance()

{

balance = 0;

return balance;

}

What tests can you run to demonstrate that it does not?

Balance is zero - therefore this value is returned.

2.54

What happens if you try to compile the TicketMachine class with the following version of refundBalance():

public int refundBalance()

{

return balance;

balance = 0;

}

What do you know about return statements that helps to explain why this version does not compile?

An error is printed: unreachable statement.

A return statement ends(exits) the method. Code after a return statement can therefore never be executed.

2.55

Add a new method, emptyMachine(), that is designed to simulate emptying the machine of money. It should return the value in total AND reset total to be zero.

public int emptyMachine() { int oldTotal = total; total = 0; return oldTotal;}

2.56

Is emptyMachine() an accessor, a mutator, or both?

It is both an accessor and a mutator.

2.57

Rewrite the printTicket() method so that it declares a local variable amountLeftToPay. This should then be initialized to contain the difference between price and balance.

Rewrite the test in the conditional statement to check the value of amountLeftToPay. If its value is less than or equal to zero, a ticket should be printed, otherwise an error message should be printed stating the amount still required.

Test your version to ensure that it behaves in exactly the same way as the original version.

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 += price; // Reduce the balance by the prince. balance -= price; } else { System.out.println("You must insert at least: " + amountLeftToPay + " more cents."); }}

I don’t Have Exercise 2.58 for some reason. . .

2.59

Draw a picture of the form shown in 2.3 representing the initial state of a Student object following its construction with the following actual parameter values:

new Student ( "Benjamin Jonson", "738321")

Name: getCode

Return type: String

2.60

What would be returned by getLoginName() for a student with the name "Henry Moore" and the id "557214"?

Name: setCredits

Parameter name: creditValue

Parameter type: int

2.61

Create a student with the name "djb" and id "859012".

What happens when getLoginName() is called on this student?

Why do you think this is?

public class Person { }

2.62

The String class defines a length() accessor method with the following signature:

public int length()

Add conditional statements to the constructor of Student to print an error message if either the length of the fullName parameter is less than 4 characters or the length of the studentId parameter is less than 3 characters. However the constructor should still use those parameters to set the name and id fields, even if the error message is printed.

Hint: use if statements of the following form (that is, having no else part) to print the error messages.

if (perform a test on one of the parameters)

Print an error message if the test returns true

private String name; private int age; private String code; private int credits;

2.63

Modify the getLoginName() method of Student so that it always generates a login name, even if either of the name and id fields is not long enough.

For strings shorter than the required length, use the whole string.

public Module { code = moduleCode; }

2.64

I don’t Have Exercise 2.64 for some reason. . .

2.65

Add two methods, printAuthor() and printTitle(), to the outline Book class.

These should print the author and title fields respectively, to the terminal window.

public int getAge() {return age;}

2.66

Add a further field, pages, to the Book class to store the number of pages. This should be of type int, and its initial value should be passed to the single constructor, along with the author and title strings.

Include an appropriate getPages() accessor method for this field.

public STring getName() { return name; }


2.67

Add a method, printDetails(), to the Book class. This should print details of the author, title and pages, to the terminal window.

It is your choice how these details are formatted. For instance, all three items could be printed on a single line, or each could be printed on a separate line.

You might also choose to include some explanatory text to help a user work out which is the author and which is the title.

public void setAge(int newAge)

2.68

Add a further field, refNumber, to the class. This field can store a reference number for a library, for example. It should be of type String and initialized to the zero length string("") in the constructor as its initial value is not passed in a parameter to the constructor. Instead, define a mutator for it with the following signature:

public void setRefNumber (String ref)

The body of this method should assign the value of the parameter to the refNumber field.

Add a corresponding getRefNumber() accessor to help you check that the mutator works correctly.

public void printDetails()


2.69

Modify your printDetails() method to include printing the reference number. However, the method should print the reference number only if it has been set - that is, the refNumber string has a non-zero length. If it has not been set, then print the string "zzz" instead.

Hint: Use a conditional statement whose test calls the length() method on the refNumber string.

student1: Student

name: Nives Michaels

id: 12345

credits: 0

2.70

Modify your setRefNumber() mutator so that it sets the refNumber field only if the parameter is a string of at least three characters. If it is less than three, then print an error message and leave the field unchanged.

“Henr557”

2.71

Add a further integer field, borrowed, to the Book class. This keeps a record of the number of times a book has been borrowed. Add a mutator, borrow(), to the class. This should update the field by one each time it is called.

Include an accessor getBorrowed(), that returns the value of this new field as its result.

Modify printDetails() so that it includes the value of this field with an explanatory piece of text.

2.72

Create a new project, heater exercise, within BlueJ.

Edit the details int the project description - the text note you see in the diagram.

Create a class, Heater, that contains a single integer field, temperature. Define a constructor that takes no parameters. The temperature field should be set to the value 15 in the constructor.

Define the mutators warmer() and cooler(), whose effect is to increase or decrease the value of temperature by 5 degrees respectively.

Define an accessor to return the value of temperature.

public Student(String fullName, String studentID){ if(fullName.length() < class="Apple-tab-span" style="white-space:pre"> System.out.println("Error! The name should be at least 4 characters long"); } if(studentID.length() < class="Apple-tab-span" style="white-space:pre"> System.out.println("Error! The studentID should be at least 3 characters long"); } name = fullName; id = studentID; credits = 0;}

2.73

Modify your Heater class to define three new integer fields: min, max and increment. The values of min and max should be set by parameters passed to the constructor. The value of increment should be set to 5 in the constructor.

Modify the definitions of warmer() and cooler() so that they use the value of increment rather than the explicit value of 5.

Before proceeding with this exercise check that everything works as before.

Now modify the warmer() method so that it will not allow a temperature to be set that is greater than max. Similarly modify cooler() so that a temperature of less than min cannot be set.

Check that the class works properly.

Now add a method, setIncrement(), that takes a single integer parameter and uses it to set the value of increment.

Once again, test that the class works as you would expect, by creating instances of Heater in BlueJ. Do things still work as expected if a negative value is passed to the setIncrement() method?

Add a check to this method to prevent a negative value from being assigned to increment.

2.74

You have now seen some examples of class, whose objects simulate the behavior of real world objects. In this exercise you should think of a different real-world object and design a class to simulate its behavior.

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


No comments:

Post a Comment