Sunday, 29 August 2010

Test Paragraph

      


       


How to create my peasant:

            To begin with, to create the peasant picture, you must have all the classes necessary to complete the body parts. The box class, which I will cover how to create further into the procedure, the triangle class, and the circle class, are all necessary classes to have before creating specific multiple instances to create the picture. To create the box class, I followed the steps given to us, in which I essentially copied the code, including the methods, constructors, and fields, of the square class, and simply changed the size field into two fields, width and height. I also had to change the overall name of the class in the code into box, and also the square words into box from the signatures of the square code. Since the triangle and circle classes are given, there was no reason to change anything within them. I then moved on to the picture class, where I would make the specific instances of each class that were needed in the picture. I needed one box for the body, two boxes for the arms, two boxes for the legs, a circle for the head, and a triangle for his hat. All the objects in the picture had different and specific parameters which were found through a basic knowledge of mathematics and graphing, as well as a lot of guess-and-check.  For the purpose of creating my exact peasant, I will include a code for each of my objects and cover what each field means:
        hat = new Triangle();
        hat.changeColor("black");
        hat.moveHorizontal(87);
        hat.moveVertical(-3);
        hat.changeSize(50, 60);
        hat.makeVisible();
       
        head = new Circle();
        head.changeColor("green");
        head.moveVertical(2);
        head.moveHorizontal(93)
        head.changeSize(50);
        head.makeVisible();
       
        body = new Box();
        body.changeColor("black");
        body.moveHorizontal(120);
        body.moveVertical(110);
        body.changeHeight(40);
        body.changeWidth(80);
        body.makeVisible();
       
        arm1 = new Box();
        arm1.changeColor("black");
        arm1.moveHorizontal(90);
        arm1.moveVertical(110);
        arm1.changeHeight(35);
        arm1.changeWidth(10);
        arm1.makeVisible();
       
        arm1 = new Box();
        arm1.changeColor("black");
        arm1.moveHorizontal(155);
        arm1.moveVertical(110);
        arm1.changeHeight(35);
        arm1.changeWidth(10);
        arm1.makeVisible();
       
        leg1 = new Box();
        leg1.changeColor("black");
        leg1.moveHorizontal(120)
        leg1.moveVertical(190);
        leg1.changeHeight(10);
        leg1.changeWidth(35);
        leg1.makeVisible();
       
        leg2 = new Box();
        leg2.changeColor("black");
        leg2.moveHorizontal(150);
        leg2.moveVertical(190);
        leg2.changeHeight(10);
        leg2.changeWidth(35);
        leg2.makeVisible();

Chapter Two Questions 2.1-2.58

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?
The value 0 is returned after printing a ticket, as the money has  been used up to buy it.
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?

 The machine, given away by the name, is naive. If you over-pay, it will not give you a refund, and will use it all up. However, on the contrary, you can insert 100 cents and still get a ticket worth 500 cents, which is why it is naive.
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?

 Yes, it does. This is because the price is different, and now on the ticket, instead of saying that it had cost 500 cents, it says it had cost 750 cents, my new price.
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.
Student: public class Student
{
Inner part
}
LabClass: public class LabClass
{
Inner part
}
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 matters, after changing it the diagram switched colors and I got an error “<identifier> expected”. It doesn’t seem to explain exactly what went wrong, but my guess is that by changing the two words, the program is looking for the word “public,” what I assume is the identifier, and is only finding the word “class.”
2.8
Check whether or not it is possible to leave out the word public from the outer wrapper of the TicketMachine class.
Apparently, omitting the word “public” doesn’t affect the outer wrapper, maybe the problem was because the program needed the outer wrapper to be “class (Class Name)” and it found earlier “class public (Class Name)” and couldn’t process a class name that isn’t only one word.
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.
Constructor: ticketCost
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?
The constructor sets values after evoking it; however, the methods only return values or a ticket in this class.
2.11
What do you think is the type of each of the following fields?
private int count
private Student representative
private Server host

 private int count is of type integer.
private Student representative is of type string.
and private Server host is also of type string.
2.12
What are the names of the following fields?
private boolean alive
private Person tutor
private Server host

 private boolean alive has is named “alive”.
private Person tutor is named “tutor”.
private Server host is named “Server host”.
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.

 The class diagram gains dashed lines from not being compiled and an error sign on it after switching the ordering of the words. This order also doesn’t compile. It seems the field has to be in the strict order of “private int price;” or it won’t function. Again the private word can be removed, but no other. The “int” specifies the type, and “price” specifies the field.
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 necessary. It is almost like a period. After every sentences, or declaration, you must show the program that the semi colon is the end of the declaration, or it will go on and combine it with another field, which then gives you an error.
2.15
Write in the full declaration for a field of type int whose name is status.
private int status;
// Shows the status of the object.

2.16
To what class does the following constructor belong?
public Student (String name)

 It belongs to class “Student.”
2.17
How many parameters does the following constructor have and what are their types?
public Book(String title, double price)

It has two parameters in the constructor. One is of type string, and the other is of 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?

Some of the Book class’s fields might be the name of the book, a string type, the author of the book, another string type, and the date it was published, which would again be a string type. If it was a book to be bought it could have an integer type for the field price, or if it was a library book it could have a code in integer type.
2.19
Suppose 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)
{
 >>
}

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?

Yes this version compiles; however, when a new object is created from the class, and a price parameter is set, there is no price value in the field. This is probably because the program could not understand the “int” part of the code before the “price = ticketCost” and simply put that field at the default integer zero as a result.
2.21
Compare the getBalance() method with the getPrice() method.
What are the differences between them?

The getBalance() and getPrice() methods, which are extremely similar in almost every way, are different in that invoking getPrice() simply returns the price a ticket, while getBalance() returns the total amount of money inside the ticket-machine at that point in its lifetime.
2.22
If a call to getPrice() can be characterized as "What do tickets cost?", how would you characterize a call to getBalance()?
I would characterize getBalance() as “How much money is in the machine right now?”
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 it doesn’t, everything that was balance simply changed to amount.
2.24
Define an accessor method, getTotal(), that returns the value of the total field.
 Done.
2.25
Try removing the return statement from the body of getPrice().
What error message do you get when you try compiling the class?

The compiler simply responds by giving an error saying it is “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 main difference between the method signatures of getPrice() and printTicket() is that getPrice() is of integer type, and printTicket() is of void type, meaning it does not return any value, rather it prints out a ticket.
2.27
Do the insertMoney and printTicket methods have return statements? Why do you think this might be? Do you notice anything about their headers that might suggest why they do not require return statements?
No, they don’t, because the word void in their headers means that it they will not have any return statements.
2.28
Create a ticket machine with a ticket price of your choosing. Before doing anything else, call the getBalance method on it. Now call the insertMoney method (Code 2.6) and give a non-zero positive amount of money as the actual parameters. Now call getBalance again. The two calls to getBalance should show different output because the call to insertMoney had the effect of changing the machine’s state via it’s balance field.
Done.



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

The word void in the setPrice() method proves that it it is a mutator method, and therefore it’s possible to know that it only alters the fields, but doesn’t create them.
2.30
Complete the body of the setPrice() method so that it assigns the value of its parameter to the price field.
Done.
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)

/**
  • Increase score by the given number of points.
  • /
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)

Yes, done.
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."

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

 Done.
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?

No they don’t because each one has a different set amount, and in my showPrice() method, I made the printed string show xyz, being the amount, as a parameter and not a set amount. Therefore, now when I make two different machines, they show different outputs, because they show different prices.
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.");

If you put quotation marks around price, it would no longer be a parameter, but a string, and all that would show up would be the word price itself instead of the integer parameter that is meant to be there.
2.37
What about the following version?
System.out.println ("# price cents.");

This is a more simplified version of the last, the word price is still in quotations, meaning it will be a string and not a variable.
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 they placed the price variable inside the string, making it no longer a variable. To make price different on each machine, it should stay the way it was, outside of quotations, so that it will still be considered a variable.
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.

Instead of having a variable, price, it is now set at 1,000 cents. Therefore each method that uses price as a variable will now have the integer value, 1,000, in its place. 
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?

No this method takes no parameters, and it is a mutator, as it changes the balance’s value to 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.

 Yes this method is a mutator as it changes the price field’s value from one into another.
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.

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

Done.
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?

 Changing the amount to greater than or equals zero simply makes it so that an error doesn’t appear when you enter 0 as a parameter. However, this doesn’t change the behavior of the method, as the balance + 0 = balance, and therefore the balance remains unchanged.
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 boolean feature controlled the visibility field, and was false when the object was not visible, and true when it was. Yes it was well suited for a type which only had two different values,i as there was one for true, and one for false.
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 naive ticket machine, the end of the printTicket() method, the total was added with the balance, which was then cleared, regardless of remaining money inside it. Now, however, the method adds price to the total, and reduces price from the balance, thereby eliminating the need to clear the balance field.
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, after a ticket has been printed, and regardless of whether it has, the balance field will never be able to be set to a negative value, or let alone subtract money from it. This is because the insertMoney() method specifically stated that amount>=0, and therefore it’s impossible to add a negative value.
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.
The Other Arithmetic Operators are:
= multiplication
/ = division
% modulus or remainder-after-division
2.49
Write an assignment statement that will store the result of multiplying two variables, price and discount, into a third variable, saving.
public Store()
{
int saving;
saving = price*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.
public Mean(int 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".

public void tooBuyorNottoBuy()
{
if(price>budget)
System.out.printIn(“Too Expensive”);
else return
System.out.printIn(“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.
 public void tooBuyorNottoBuy()
{
if(price>budget)
System.out.printIn(“Too Expensive, Current Budget:” + budget);
else return
System.out.printIn(“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?

 This refundBalance() method simply clears balance, and returns it after after being cleared, meaning it’s value will always be returned as 0. You can try changing the method to this, creating an instance, calling the insertMoney() method, and then calling the returnBalance() method in order to check this.
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?

It won’t compile because methods that return values always have to have the return block at the end of the method.
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.
 Done.
2.56
Is emptyMachine() an accessor, a mutator, or both?
It is a mutator because it changes the state of the object, and doesn’t return a message, rather it returns a printed message, which is different. Furthermore, it doesn’t tell us about the object, we just programmed the print message to say something that does.
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.

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

pastedGraphic.pdf
2.60
What would be returned by getLoginName() for a student with the name "Henry Moore" and the id "557214"?
 The value returned by getLoginName() for the student would be “Henr557”.
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?

 It brings up the compiler, explaining that the range of the getLoginName() method is too large for student instance “djb”, and therefore the method cannot be called.
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

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

Done.
2.64


 Done, made methods getTitle() and getAuthor().
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.

 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 be passed 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 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.

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

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

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

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

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

Done and modified increment to not be a negative integer value.
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.
 Done.

All chapter two questions are done, and are above.