Sunday 12 September 2010

Chapter 2 Questions

Barnes and Kolling Chapter Two 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
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 more than the exact amount you do not get any change and the balance goes to zero. When you put less than the amount needed it still prints the ticket and the balance returns to zero.
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.
 Done
2.5
Create another ticket machine for tickets of a different price. Buy a ticket from that machine.
Does the printed ticket look different?

 Ticket looks the same.
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
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?

 Identifier expected. This message states that the order is incorrect.
2.8
Check whether or not it is possible to leave out the word public from the outer wrapper of the TicketMachine class.
 Possible. Class compiled no error
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 thefieldsconstructors, and methods in theTicketMachine class.
Hint: There is only one constructor in the class.

 Constructor:
Public ticketmachine (int ticketcost)

Field:
// The price of a ticket from this machine.
Private int price; ………………………………………..
…………

Private int total;

Methods:
All others
2.10
Do you notice any features of the constructor that makes it significantly different from the other methods of the class?
The constructor creates the object, others don’t.
2.11
What do you think is the type of each of the following fields?
private int count
private Student representative
private Server host

 1) type int
2) type
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.

 <identifier> expected
The order does matter.
The ticket machine class had lines in it
   It does not 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.
 Semicolon is a must
Cannot compile without it!
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)

 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?

 ???
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)
{
 >>
}

 Public petsName (string name)
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?

 ticketCost in not an int
2.21
Compare the getBalance() method with thegetPrice() method.
What are the differences between them?

 Getbalance tells you how much money is in the machine
Getprice tells you cost of ticket
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 is in the 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, class compiled and it works same as before
2.24
Define an accessor methodgetTotal(), thatreturns the value of the total field.

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 ofgetPrice() and printTicket() in code 2.1.
Apart from their names, what is the main difference between them?

 Get price only return a value
printTicket return a picture and makes the balance go back to 0
2.27
How can we tell from just its header thatsetPrice() is a method and not aconstructor?
public void setPrice(int ticketCost)

 It has ()
The ability to put int






2.29
How can we tell from just its header thatsetPrice() is a method and not aconstructor?
public void setPrice(int ticketCost)

 It has ()
The ability to put int
2.30
Complete the body of the setPrice() method so that it assigns the value of itsparameter to the price field.
 ok
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)

 ok
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 – 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."

 Ok

Public void Prompt()
{
System.outprintln (“please return the correct amount of money”);
}
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.

 Ok
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 different output. Each one shows the int or price I gave.
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.");

 It would not show a number,
It would show the string “price”
2.37
What about the following version?
System.out.println ("# price cents.");

 Same as before
So actual 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, the ticket machine needs to give us a price and in any scenario where you put price in quotations it does not give a price number value
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.

 ok
2.40
Implement a methodempty(), 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?

 Method works
   
    public void empty()
   
    {
        balance = 0;
       
    }
   
No parameters, it is a mutator
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.

 public void setPrice(int newPrice)
   
    {

        price= newPrice;
       
       
        }
It is a mutator since it changes the field of price
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.

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

 The balance does not change if there is error, but if the ticket is printed the value remains the same

The ticket costs 0 cents, essentially the ticket is free so you may buy endless tickets for no money
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?

 public void insertMoney(int amount)
    {
        balance = balance + amount;
       
        if (amount>=0);
    }
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?

 It only gave you two value options
Yes it was
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.

 There is a difference in the insertmoney method. In code 2.8 we added public void insertMoney(int amount)
    {
        balance = balance + amount;
       
        if (amount>=0);
else {
System.out.println (“use a positive amount: “ + amount) ;
    }
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 it doesn’t allow
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.
 done
2.49
Write an assignment statement that will store the result of multiplying two variables,price and discount, into a third variable,saving.

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

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)
return
System.out.println ( “too expensive”) + budget;
Else return
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.
 Done in previous exercise
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?

 It does not return an int value,
And it initializes the value of balance to zero
It does not return to amountorefund but only the balance

Compared it to code 2.8
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 statementsthat helps to explain why this version does not compile?


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.

2.56
Is emptyMachine() an accessor, a mutator, or both?
 It is 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.







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")



Don’t understand instructions..
2.60
What would be returned by getLoginName() for a student with the name "Henry Moore" and the id "557214"?
“ Henr557”
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?

 It is an error since the substring is told to go to the fourth character
Which in this case does not exist
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


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.

   public String getLoginName()
    {
If ( name.length() >=4 && id.length >= 4 )
        return name.substring(0,4) + id.substring(0,3);

else return name + id;
    }
2.64


2.65
Add two methodsprintAuthor() andprintTitle(), to the outline Book class.
These should print the author and title fields respectively, to the terminal window.

   public void printAuthor ()
   
    {
    System.out.println (author);
   
}



    public void printTitle ()
   
    {
        System.out.println (title);
       
    }
2.66
Add a further fieldpages, 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.

   /**
     * return number of pages
     */
   
    public int getpages (int pages)
    {
        return pages;
       
    }
2.67
Add a methodprintDetails(), to the Bookclass. This should print details of theauthortitle 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.

/**
     * prints all book details
     */
   
   
    public void print()
   
    System.out.println(title + author + pages);
      
       
    }
2.68
Add a further fieldrefNumber, 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.

 Not compiling
Not sure why
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.

 If (str.length() >0)
Return refNumber
Else return “zzz”
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 successfully
2.71
Add a further integer fieldborrowed, to theBook class. This keeps a record of the number of times a book has been borrowed. Add a mutatorborrow(), 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 successfully
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 classHeater, that contains a single integer fieldtemperature. 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.

 public Heater()
    {
       tempature = 15;
     
    }
   
    public int warmer()
   
    {
        return tempature + 5;
    }

    public int cooler()
   
    {
        return tempature - 5;
    }
   
    public int getTempature()
    {
   
    return tempature;
}
   
2.73
Modify your Heater class to define three new integer fieldsminmax 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 methodsetIncrement(), 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.

 Not working
Cannot understand why…
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