Wednesday, September 15, 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.

Done.

2.2

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

0 cents

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 we insert too much money, it takes only the amount we assigned in the beginning and if we don’t insert enough money, it still prints 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.

Yes, I do have a good understanding.

2.5

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

Does the printed ticket look different?

Yes, the price changes.

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.

public class Student

{

}

And

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 it does matter what we write in the outer wrapper of a class.

Yes there is a change in the class diagram. We see an error sign on the diagram.

We get “ expected”

This is because after ‘class’ we are required to put the name of the class. For example ‘student’ or ‘TicketMachine’. However, public is not a class but a default which is why we get an error.

2.8

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

Checked! It is possible as when we compile, it says “no syntax errors”.

It doesn’t matter if we write ‘public’ or not because it is defaulted so even if we don’t write it, it’s still there.

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 thefields, constructors, and methods in theTicketMachine class.

Hint: There is only one constructor in the class.

The fields – price, balance, total

Constructers – TicketMachine

Methods – getPrice (), get Balance (), insertMoney (), printTicket ()

2.10

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

The constructor has name as the class in which they are defined. In this case, its TicketMachine. In addition to that, the inner wrapping of constructor has all fields included together whereas in methods, we see those fields individually. Example in TicketMachine, the inner wrapping of constructor includes price, balance and total. On the other hand, in methods, in getPrice () we find one of the fields that is price. In getBalance (), we find balance and in printTicket () we find the total.

In other words simpler words, a constructor just doesn’t do an action but creates a machine or a program.

2.11

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

private int count

private Student representative

private Server host

Type int or integer

Type student

Type server

2.12

What are the names of the following fields?

private boolean alive

private Person tutor

private Server host

alive

tutor

host

2.13

In the following declaration from theTicketMachine 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.

When we put –

1. price int private – we get expected. Also in the class diagram, there is an error sign.

2. private int price – we get class compiled.

3. int price – we get class compiled.

4. price int – we get expected and an error sign in the class diagram.

Conclusion – it doesn’t matter if we write ‘private’ or not since it has been defaulted so even if we don’t write, it exists. Also ‘price’ HAS to exist after int. In other words, the field always has to be placed after data type. Also, yes, we get an error sign “!” if there is an error when we compile.

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 there is necessary to have a semicolon at the end of a field or it gives an error.

2.15

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

Private int status;

2.16

To what class does the followingconstructor belong?

public Student (String name)

Class student

2.17

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

public Book(String title, double price)

It has two parameters:

1) title which is type string.

2) price which is type double.

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?

Possible fields’ types and their possible names– int (page number, year it was published in), string (color, name), double (length of the book, price)

2.19

Supose that the class Pet has a field called name that is of type String. Write anassignment in the body of the followingconstructor so that the name field will beinitialized with the value of theconstructor'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-machineproject.

Does this version compile?

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

Can you explain why this is?

There should be no ‘int’ before price because you have already specified the field type when the field was declared in the beginning.

However, when we tried this in naive-tocket-machineproject, the class complied.

That’s because when we put "int" in front of price, it creates a new variable that is different from the field price.

2.21

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

What are the differences between them?

getBalance() is how much money we put and getPrice() is how much money we insert while creating the ticketmachine. In other words, getBalance() method returns the balance and getPrice() method returns the price.

2.22

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

getBalance() can be characterized as “what is the balance of the ticket machine?”

2.23

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

Try it out within BlueJ.

No it doesn’t because the file gets compiled with no syntax errors.

2.24

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

A method that prints information about an object’s state is classified as an accessor method. In other words, accessor methods return information about the state of an object.

public int getTotal()

{

return;

}

2.25

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

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

It says “missing return statement”

2.26

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

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

printTicket() doesn’t have a return statement. In other words, getPrice() is type int and an accessor. Whereas printTicket() is void and mutator.

2.27

How can we tell from just its header thatsetPrice() is a method and not aconstructor?

public void setPrice(int ticketCost)

A constructor has a single formal parameter which in this case is ticketCost. Whereas the method has none but just a pair of empty parenthesis. And since setPrice() has no parameter but just empty parathesis, we can say that it’s a method and not a constructor.

(same question repeated twice)

2.29

How can we tell from just its header thatsetPrice() is a method and not aconstructor?

public void setPrice(int ticketCost)

A constructor has a single formal parameter which in this case is ticketCost. Whereas the method has none but just a pair of empty parenthesis. And since setPrice() has no parameter but just empty parathesis, we can say that it’s a method and not a constructor.

2.30

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

{

price = ticketCost;

}

2.31

Complete the body of the following method, whose purpose is to add the value of itsparameter 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 itsparameter from a field named price?

public void discount (int amount)

Discount = price – (int amount)

2.33

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

"Please insert the correct amount of money."

Done. Class compiled with no syntax errors.

2.34

Add a showPrice() method to theTicketMachine class. This should have avoid 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 valueheld in the price field when the method is called.

Added!

/**

* The price of a ticket is ticketCost cents

*/

public void showPrice()

{

System.out.println("The price of a 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?

They show the different output.

2.36

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

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

The ticket says “price cents” instead of giving us a numerical value.

2.37

What about the following version?

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

It also gives “price cents” instead of a numerical value.

2.38

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

Explain your answer.

It always prints whatever is there in the quotation marks. Therefore it would print "# price cents.”

2.39

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

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

Earlier, when constructor had a parameter and we tried to construct ticket machine object, it asked for ‘new TicketMachine’ where we had to set the price. However, if we remove the parameter and fix the price to be 1000 and then try to construct an object, it asks for ‘Name of Instance’ and when we check the price, it gives 1000 which was already stored in the method.

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 anyparameters?

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?

No this method doesn’t need to take any parameters.

This method is a mutator and not a accessor because there is no return statement involved in the method.

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

It’s a void method and therefore has no return statement involved. Therefore, this method is a mutator.

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 adefault value of your choosing.

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

public TicketMachine(int ticketCost)

{

price = ticketCost;

balance = 0;

total = 0;

}

public TicketMachine ()

{

price = 20;

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

No the balance doesn’t change even if an error message is printed.

If we enter 0, it says ‘use a positive amount: 0’

2.44

Predict what you think will happen if you change the test in insertMoney() to use thegreater-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 would accept 0.

In the previous exercise, when it was greater than 0, the positive amount started from 1. However in this case, since it’s greater than or equal to 0, the positive amount starts from 0. In previous example, we get an error ticket if we insert 0 whereas in this one, if we insert 0 cents, we get a printed ticket.

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 atype with only two different values?

The feature was to make circle visible or invisible.

Yes it was well suited to being controlled by a type with only two different values.

2.46

In this version of printTicket() we also do something slightly different with the totaland 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.

The main differences are –

- In code 2.8, a ticket can only be printed if enough money has been inserted or else an error message is printed. On the other hand, in 2.1, the ticket gets printed no matter what. Meaning, in 2.8, a conditional method as been added.

- In 2.8, it reduces the balance by the ticket prince after the ticket has been printed. Whereas in 2.1, the balance is set to 0 once the ticket is printed.

- In 2.1, the positive amount starts from 1 (since it’s greater than 0). Whereas in 2.8, the positive amount starts from 0 (since it’s greater than OR equal to zero)

- In 2.1, total = total + balance. In 2.8, total = total + price

- In 2.1, balance = 0.

In 2.8, balance = balance – 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.

No because if the value in balance field is ever be set to a negative, for example (-17) then that means we need to put in 17 more cents. If the balance value is negative, it means that price value is less than what it should be and therefore the ticket won’t be printed.

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.

Other operators available are – *, /, and %.

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*discount

2.50

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

mean = total/count

2.51

Write an if statement that will compare thevalue 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. Budget =” budget);

}

else

{

System.out.println (“Just right”);

}

2.53

Why does the following version ofrefundBalance() 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?

Originally amountToRefund = balance;

And therefore whatever the extra money we put in the machine is same as the balance.

However in the given version, balance = 0 and therefore no matter how much extra money we put in, we get a 0 balance.

To demonstrate this, I took off the first two lines from the original source code and noticed that the balance came out to be 0 and noticed when the whole original thing was there, it gave me a value greater than 0.

Or in other words, there is no local variable which is why it doesn’t give the same result.

2.54

What happens if you try to compile theTicketMachine 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?

When we try to compile the given version, it gives an error which says “unreachable statement”. This is because we know a method ends with a return statement if its type int and in this version, the method didn’t end with a return statement. On the other hand if you try the following version:

public int refundBalance()

{

balance = 0;

return balance;

}

You will notice that this version gets complied without any syntax errors.

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.

Added and complied.

public int emptyMachine(int total)

{

return total = 0;

}

2.56

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

It's both.

2.57

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

Rewrite the test in the conditional statementto 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.

Done!

2.59

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

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

Name: Benjamin Jonson

ID: 738321

Login name: benj738

2.60

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

“Henr557” should be returned.

2.61

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

What happens when getLoginName() iscalled on this student?

Why do you think this is?

When getLoginName() is called on this student it gives an error saying “StringIndexOutOfBoundsException: String index out of range: 4 (in java.lang.String)”

This is because the string length for name is (0,4) which means a name needs to have at least 4 chars in it whereas the name has only 3 chars in it. To prove it, we can go to the source code and change the name.substring to (0,3). Now if we call getLoginName(), we get “djb859”

2.62

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

public int length()

Add conditional statements to theconstructor of Student to print an error message if either the length of the fullNameparameter 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 thename 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

Done!

2.63

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

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

Done!

2.64

2.65

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

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

Done!

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 bepassed to the single constructor, along with the author and title strings.

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

Done!

2.67

Add a method, printDetails(), to the Bookclass. This should print details of theauthor, 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.

Done!

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 valueis not passed in a parameter to theconstructor. 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 mutatorworks correctly.

Done!

2.69

Modify your printDetails() method to include printing the reference number. However, themethod should print the reference number only if it has been set - that is, therefNumber 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 refNumberstring.

Done!

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.

Done!

2.71

Add a further integer field, borrowed, to theBook 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 iscalled.

Include an accessor getBorrowed(), thatreturns 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.

Done!

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 aconstructor that takes no parameters. Thetemperature 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 oftemperature.

Done!

2.73

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

Modify the definitions of warmer() andcooler() so that they use the value ofincrement 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 mincannot 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 ofHeater in BlueJ. Do things still work as expected if a negative value is passed to thesetIncrement() method?

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

Done!

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.

No comments:

Post a Comment