Monday, 27 September 2010

CS Chapter Four Problems 4.1-4.21


Barnes and Kolling Chapter Four Questions
Barnes and Kolling Chapter Four Questions


1
Open the notebook1 project in BlueJ and create a Notebook object.
Store a few notes into it - they are simple strings - then check that the number of notes returned by numberOfNotes() matches the number that you stored.
When you use the showNote() method, you will need to use a parameter value of zero to print the first note, one to print the second note and so on.

 I made two notes (reminders) as shown in the terminal window, and the int number of notes matches the amount I had created:

2
If a collection stores 10 objects, what value would be returned from a call to its size() method?
 It would return 10.
3
Write a method call using get() to return the fifth object stored in a collection called items.
 public ArrayList getNote(int n)
{
     if(0>n){
}
     else return notes[n];
}
4
What is the index of the last item stored in a collection of 15 objects?
 Its index would be 14.
5
Write a method call to add the object held in the variable meeting to a collection called notes.
 public void storeNote(String meeting)
{
    notes.add(meeting);
}
6
Write a method call to remove the third object stored in a collection called dates.
 {
   dates.remove(2);
}
7
Suppose that an object is stored at index 6 in a collection.
What will be its index immediately after the objects at index 0 and index 9 are removed?

 After removing:
Index 0, Index 6 will become Index 5.

Index 9, Index 6 will stay Index 6.
8
Implement a removeNote() method in your notebook.
 Here is my method's code:
/**
     * Remove a note.
     */
    public void removeNote(int noteNumber)
    {
        if(noteNumber<0)
        {
        }
        else if(noteNumber<notes.size())
            notes.remove(noteNumber);
        else{
        }
    }
9
What might the header of a listAllNotes() method look like?
What sort of return type should it have?
Does it need to take any parameters?

 public void listAllNotes()
This method needs a void return type, since we would print the notes out, and requires no parameters, as its returning ALL notes.
10
We know that the first note is stored at index zero in the ArrayList, so could we write the body of listAllNodes() along the following lines?
        System.out.println(notes.get(0));
        System.out.println(notes.get(1));
        System.out.println(notes.get(2));   etc.

 No we could not. This is because we can't predetermine the amount of notes to be created, and therefore we will need to set a parameter.
11
Implement the listNotes() method in your version of the notebook project
 Here's what it looks like:
12
Create a Notebook and store a few notes in it.
Use the listNotes() method to print them out to check that the method works as it should.

 Skip two notes, those are from before, and you'll see all of my notes printed:

13
If you wish you could use the debugger to help yourself understand how the statements in the body of the while loop are repeated. Set a breakpoint just before the loop, and step through the method until the loop's condition evaluates to false.
 At the end of the method after the evaluation was false:

14
Modify showNote() and removeNote() to print out an error message if the note number entered was not valid.
 There are the two error messages that I created in the terminal window:

15
Modify the listNodes() method so that it prints the value of the index local variable in front of each note. For instance:
        0: Buy some bread
        1: Recharge phone
        2: 11:30 Meeting with Annabel
This makes it much easier to provide the correct index when removing a note.

 The result:

16
Within a single execution of the listNodes() method, the notes collection is asked repeadly how many notes it is currently storing. This is done every time the loop condition is checked.
Does the value returned by size() vary from one check to the next? If you think the answer is "No", then rewrite the listNodes() method so that the size of the notes collection is determined only once and is stored in a local variable in the loops condition rather than the call to size().
Check that this version gives the same results.

 It worked, although in different circumstances size can change, if you make it do so. However, in this case it doesn't, and it worked.
17
Change your notebook so that the notes are numbered starting from 1, rather than zero. Remember that the arrayList object will still be using indices starting from zero, but you can present the notes numbered from 1 in your listing.
Make sure you modify showNote() and removeNote() appropriately.


 Modified:


18
Some people refer to if statements as if loops.
From what we have seen of the operation of a while loop, explain why it is not appropriate to refer to if statements as loops.

 While is stating that during the time that the condition is met, do this loop, but if is asking whether the condition is being met, and if so, then do the loop..
19
Use the club project to complete the following exercises.
Your task is to complete the Club class, an outline of which has been provided in the project. The Club class is intended to store Membership objects in a collection.
Within Club, define a field for an Arraylist. Use an appropriate import statement for this field.
Make sure that all the files in the project compile before moving on to the next exercise.

 Done:

20
Complete the numberOfMembers() method to return the current size of the collection.
Until you have a method to add objects to the collection this will always return zero, of course, but it will be ready for further testing later.

 Done:

21
Membership of  a club is represented by an instance of the Membership class. A complete version of Membership is already provided for you in the club project, and it should not need any modification. An instance contains details of a person's name, and the month and year in which they joined the club. All membership details are filled out when an instance is created. A new Membership object is added to a Club object's collection via the Club object's join() method which has the following signature.
public void join(Membership member)
Complete the join() method
When you wish to add a new Membership object to the Club object from the object bench, there are two ways you can do this.
Either create a new Membership object on the object bench, call the join() method on the Club object, and click on the Membership object to supply the parameter;
..or call the join() method on the Club object and type into the constructor's parameter dialog box:
new Membership("member's name ",month, year)
Each time you add one, use the numberOfMembers() method to check both that the join() method is adding to the collection, and that the numberOfMembers() method is giving the correct result.

 Done, this is the script I ended up with including all the steps, and working:
import java.util.ArrayList;
/**
 * Store details of club memberships.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class Club
{
    private ArrayList members;
   
    /**
     * Constructor for objects of class Club
     */
    public Club()
    {
        members = new ArrayList();
    }

    /**
     * Add a new member to the club's list of members.
     * @param member The member object to be added.
     */
    public void join(Membership member)
    {
        members.add(member);
    }

    /**
     * @return The number of members (Membership objects) in
     *         the club.
     */
    public int numberOfMembers()
    {
        return members.size();
    }
}

Wednesday, 22 September 2010

Chapter Three Continued


3.39
Set a breakpoint in the first line of the sendMessage() method in the MailClient class. Then invoke this method.
Use the Step Into function to step into the constructor of the mail item. In the debugger display for the mail item object, you can see the instance variables and local variables that have the same names, as discussed in section 3.12.2.
Step further to see the instance variables get initialized.

 Here is a picture of the local and instance variables getting initialized as I stepped into the method further:

3.40
Use a combination of code reading, execution of methods, breakpoints, and single stepping to familiarize yourself with the MailItem and MailClient classes.
Explain how the MailClient and MailItem classes interact.
Draw object diagrams as part of your explanations.

 The MailClient class interacts with the MailItem class by relying on it as a reference. The MailClient object in fact uses the MailItem class in order to move it’s messages, or results of its method, to other object. Here is an object diagram of their interaction:

3.41
Use the debugger to investigate the clock-display project.
Set breakpoints in the ClockDisplay constructor and in each of the methods, and then single-step through them.
Is the behavior what you expected?
Did this give you new insights? If so what were they?

Yes, the behavior which I expected was for the ClockDisplay class to open up the NumberDisplay class for each of its methods in order to receive the actual parameters for the objects it was referencing. This was exactly what happened.
3.42
Use the debugger to investigate the insertMoney() method of the better-ticket-machine project from chapter 2.
Conduct tests that cause both branches of the if statement to be executed.

 This is a picture of a half printed ticket, while single-stepping into the printTicket() method:

3.43
Add a subject line for an e-mail to mail items in the mail-system project.
Make sure printing messages also prints the subject line. Modify the mail client accordingly.

 Here is a picture of a printed message with the newly created subject field represented. It simply has to be entered such as any other String field in the MailItem class, such as “to,” “from,” and “message”:

3.44
Given the following class..

public class Screen
{
 public Screen (int xRes, int yRes)
 {}
 public int numberOfPixels()
 {}
 public void clear(boolean invert)
 {}
}
Write some lines of Java code that creates a Screen object, and then call its clear() method if and only if its number of pixels is gretaer than 2 million

 The following is the source code of the class which I created, and which functions with all of the above methods:

/**
 * Class Screen
 *
 * @author (Michael)
 * @version (2.147)
 */
public class Screen
{
    // instance variables - replace the example below with your own
    private int xRes;
    private int yRes;

    /**
     * Constructor for objects of class Screen
     */
    public Screen(int xres, int yres)
    {
        xRes = xres;
        yRes = yres;
    }

    /**
     * Constructor Default for Screen.
     */
    public Screen()
    {
        xRes = 0;
        yRes = 0;
    }
   
    /**
     * Return the number of pixels
     */
    public int numberOfPixels()
    {
        return xRes*yRes;
    }
   
    /**
     * Clear.
     */
    public void clear(boolean invert)
    {
        int pixels = xRes*yRes;
        if(invert)
        {
            if(pixels >= 2000)
                 pixels = 0;
        }
        else System.out.println("There aren't enough pixels to clear the Screen, please enter more pixels and retry.");
    }
}



Monday, 13 September 2010

Chapter Three Questions 3.1-3.44


3.1
Think again about the lab-classes project that we discussed in Chapter 1 and Chapter 2. Imagine that we create a LabClass object and three Student objects. We then enroll all three students in that lab. Try to draw a class diagram and an object diagram for that situation.
Identify and explain the differences between them.

Static view:
Object Diagram:


3.2
At what time(s) can a class diagram change?
How is it changed?

 A class diagram can change whenever a new class is added into the project in order to complete another task. When a new class enters the class diagram, or static view, and becomes a new dependency for the “general class.”
3.3
At what time(s) can an object diagram change?
How is it changed?

 On the other hand, object diagrams change whenever a new object is created, and therefore the class diagram can stay the same, while the object diagram changes. When this happens, a new object becomes a reference to the “general object.”
3.4
Write a definition for a field named tutor that can hold references to objects of type Instructor.
 private Instructor tutor;
3.5
Start BlueJ, open the clock-display example and experiment with it. To use it, create a ClockDisplay object, then open an inspector window for this object. With the inspector open call the object's methods. Watch the displayString field in the inspector.
Read the project comment (by double-clicking on the text note icon on the main screen) to get more information.

3.6
What happens when the setValue() method is called with an illegal value?
Is this a good solution?
Can you think of a better solution?

 The value simply remains the same. Obviously this is not a good solution, as it does not print out an error to notify the user. A better solution would be to print an error saying “Please enter a value for hours that is between 0-23 and for minutes between 0-59.”
3.7
What would happen if you replaced the ">=" operator in the test with ">", so that it read..
  if((replacementValue > 0) && (replacementValue < limit))

 If you would remove the “=” sign from the “>=” operator, it would simply read greater than instead of greater than or equal to. As a result, the hour value or the minute value could never be zero, which it must at certain times.
3.8
What would happen if you replaced the "&&" operator in the test with "||", so that it read..
  if((replacementValue >= 0) || (replacementValue < limit))

 If you replaced the “&&” operator with “||” you’re essentially saying that one of the conditions can be met, while the other potentially can not be met. In this case, you would allow an illegal value to be stored, so long as at least one of the conditions have been met.
3.9
Which of the following expressions return true?
! (4<5)
! false
(2>2) || ((4==4) && (1<0))
(2>2) || (4==4) && (1<0)
(34 !=33) && ! false


 !false returns a true statement as it’s saying “what’s NOT false.” The answer obviously is true.
3.10
Write an expression using boolean variables a and b that evaluates to true when either a and b are both true or both false.
 if(a=true && b=true)
    return true;
else if(a=false && b=false)
     return true;
else return false;
3.11
Write an expression using boolean variables a and b that evaluates to true when only one of a or b is true, and which is false if a and b are both false or both true. (This is also called an exclusive or.)
 if(a=true && b=true)
    return false;
else if(a=false && b=false)
    return false;
else return true;
3.12
Consider the expression (a && b).
Write an equivalent expression (one that evaluates to true at exactly the same values for a and b) without using the && operator.

if(!a || !b) 
     return false;
else return true;
3.13
Does the getDisplayValue() method work correctly in all circumstances?
What assumptions are made witrhin it?
What happens if you create a number display with limit 800, for instance?

It does, but with incorrect values. Entering values greater than 23 makes the method give illegal values. Entering a value of 800, for example, becomes tricky, as the getDisplayValue() method does not specify that the value must be within the range of 0-23.
3.14
Is there any difference in the result of writing
        return value + "";
Rather than
        return "" + value;
in the getDisplayValue() method?

 No, because in both cases the integer value is still being concatenated with a string value, thus changing the integer value into a string, and since the string “” is empty, it doesn’t change the order of the resulting string.
3.15
Explain the modulo operator.
 The mudolo operator simply takes a fraction and changes it into a proper fraction in which it factors out all the whole numbers thus creating two resulting categories; a result and a remainder category. The mudolo operator is only concerned with the remainder and therefore only returns that from the proper fraction. In the example 4%3 the returned value would be 1, as 3/3 + 1/3 is the same, and 3/3 is the result whereas 1/3 is the remainder. It takes the value of 1 from the remainder and keeps it.
3.16
What is the result of the evaluation of the expression (8%3)?
 2 is the result.
3.17
What are all possible results of the expression (n%5), where n is an integer variable?
All the possible results are 0, 1, 2, 3, 4, but not 5, as 5/5 is no remainder.
3.18
What are all possible results of the expression (n%m), where n and m are integer variables.
 The results, I will define a variable for it, k, are any integers in the restriction
0<= k < m.
3.19
Explain in detail how the increment() method works.
 The purpose of the increment() method is to reset the value to zero once the limit is reached. The way it works is, it adds 1 to the value (when it is 23) to form 24 and then modulates it with the limit, 24. Therefore, the remainder of 24/24 is 0, and the returned value to reset the clock to zero is simply 0.
3.20
Rewrite the increment() method without the modulo operator, using an if statement.
Which solution is better?

 if(value>23)
value = 0;
I believe the better solution is to use the if statement, as the increment() method does not consider whether the value was,  for example, 75, where adding 1 to 75 would return and then 76 % 24 would not return a remainder 0, and therefore could reset the clock to an illegal value. Obviously the other methods in the class rule this out, but generally the boolean expression would not even need that help.
3.21
Using the clock-display project in BlueJ, test the NumberDisplay class by creating a few NumberDisplay objects and calling their methods.


3.22
Create a ClockDisplay object by selecting the following constructor:
        new ClockDisplay()
Call its getTime() method to find out the initial time the clock has been set to.
Can you work out why it starts at that particular time?

 The clock starts at that particular value because the actual parameters defined in the class source code exceed the limit defined in the NumberDisplay class. Recall that the hours integer can’t reach over 23 and the minutes can’t reach over 59; however, in this case we defined the actual parameters as 24 and 60, which again, exceed the limit, therefore setting them at 0.
3.23
How many times would you have to call the tick() method on a newly created ClockDisplay object to make its time reach 01:00?
How else could you make it display that time?

You would have to call the tick() method 60 times to get it to 1:00. On the contrary, you can simply set the time to 1:00 by calling the setTime() method.
3.24
Write the signature of a constructor that matches the following object creation instruction:
new Editor ("readme.txt, -1)

 public Editors() - I cannot understand why this is only asking for the signature? As I see it, the signature for a constructor that creates an object of another class is simple, I will ask about this tomorrow in class.
3.25
Write Java statements that define a variable named window of type Rectangle, and then create a rectangle object and assign it to that variable. The Rectangle constructor has two int parameters.
 public House(Rectangle window)
{
        window = newRectangle(9, 5)
}
3.26
Look at the second constructor in ClockDisplay's source code.
Explain what it does and how it does it.

 What the second constructor in ClockDisplay’s source cody does is begin a clock based on parameters that have to be set by the user. It does this by defining two formal parameters of type int, hour and minute, and later defining them to be set by the user.
3.27
Identify the similarities and differences between the two constructors.
Why is there no call to updateDisplay() in the second constructor, for instance?

 The similarities are that both the hours and minutes fields are defined in both cases to above the limit they can hold (24 and 60) in both case. The differences are that the second constructor has formal parameters, and the first constructor has a block, updateDisplay(); whereas the second constructor instead has setTime( hour, minute);. There is no updateDisplay() in the second constructor because the clock doesn’t have to be updated to 00:00 since the user will anyhow be setting new values.
3.28
Given a variable

Printer p1;

which currently holds a printer object, and two methods inside the Printer class with the headers

public void print(String filename, boolean doubleSided)
public int getStatus(int delay)

write two possible calls to each of these methods.
 A possible call to the public void print() is:
{
String filename = “File”;
if(“File” = doubleSided)
   return System.out.println(“File is double-sided”);
else return System.out.println(“File is not double-sided”);
}
A possible call to the public int getStatus(int delay) method is:
{
delay = glitch;
return delay;
}

3.29
Change the clock from a 24-hour clock to a 12-hour clock.
Be careful: this is not as easy as it might at first seem.
In a 12-hour clock the hours after midnight and after noon are not shown as 00:30, but as 12:30. Thus the minute display shows values from 0 to 59, while the hour display shows values from 1 to 12.


All that had to be changed was the value 24 in the two constructors above, to a value of 13.
3.30
There are at least two ways in which you can make a 12-hour clock. One possibility is to just store hour values from 1 to 12. On the other hand, you can just leave the clock to work internally as a 24-hour clock, but change the display string to show 4:23, or 4:23pm when the internal value is 16:23.
Implement both versions.
Which option is easier? Why?
Which option is better? Why?

 The easier option is to store values from 1 to 12 as then you do not have to show the pm or am part of the time; however, the better one is still the one that shows whether the time is am or pm as it gives more information.

3.31
Open the mail-system project, which you can find in the book's support material.
Create a MailServer object.
Create two MailClient objects. When doing this you need to supply the MailServer instance, which you just created, as a parameter. You also need to specify a username for the mail client.
Experiment with the MailClient objects. They can be used to send messages from one mail client to another (using the sendMessage() method) and to receive messages (using the getNextMailItem() or printnextMailItem() methods).

 Here’s an example of a message I sent to “Billybobjo” (I’m user “Dude”) :

3.32
Draw an object diagram of the situation you have after creating a mail-server and three mail clients.
 The following is an object diagram of one mail-server and three mail clients. The arrows indicate objects belonging in another object’s field(s):

3.33
Set up a scenario for investigation: Create a mail server, then create two mail clients for the users 'Sophie' and 'Juan'.
Then use Sophie's sendMessage() method to send a message to Juan.
DO NOT YET READ THE MESSAGE.

 Here is a picture of the message before I had sent it from Sophie to Juan:

3.34
Open the editor for the MailClient class and set a breakpoint at the first line of the printNextMailItem() method.
 Here is what the source code looks like after setting a breakpoint:

3.35
Step one line forward in the execution of the printNextMailItem() method by clicking the Step button.
 After stepping only once:

3.36
Predict which line will be marked as the next line to execute after the next step. Then execute another single step and check your prediction.
Were you right or wrong? Explain what happened and why.

 I believe the line after the boolean expression will be marked after stepping once more, because the boolean is like one entity, one piece of the method.
I was partially right, and partially wrong. It DID consider the first if statement as one line, but it didn’t skip until after the ENTIRE boolean statement. The arrow stopped right before the else return statement. This further illustrates what I’m saying:
3.37
Call printNextMailItem() again.
Step through the method again, as before.
What do you observe? Explain why this is.

 This time, the method went to the first part of the boolean statement, where the item was equal to null, nothing. This is because we Juan already received the message from Sophie, and there’s no new message. If there was a new message, item would not be null, and it would print out the message instead of printing out “No new mail.”
3.38
Set up the same test situation as we did before. That is, send a message from Sophie to Juan. Then invoke the printNextMailItem() method of Juan's mail client again. Step forward as before. This time, when you read the line
        item.print()
use the Step Into command instead of the step command. Make sure you can see the text terminal window as you step forward.
What do you observe? Explain what you see.

 Nothing prints in the text terminal after using step into at line item.print(). However, a copy of the MailItem class source code pops up, highlighting the first line of it’s print() method. The arrow is on that collumn, which probably means, we stepped further into the code, with a reference to this object, which now means that we have to fully invoke this method in order to finish calling the printNextMailItem() method.