Monday, 6 December 2010

Chapter 10 Test

6. Now run your simulation. How does the introduction of gender impact the changing populations? Make a quantitative comparison of V2 and V3.


Here it is possible to see the differences between breeding rates in v2 and v3 quantitatively:

These screenshots are the numbers of rabbits after 200 steps (male vs. female)

v2:


v3:


7. Given what you have learned from V3, describe one way of extending the simulation in "V4". What hypothesis will you be testing with V4?
     For V4 it is possible to implement a class Grass off of which the rabbit survives. Just as the fox class searches for rabbits, rabbits should, too, search for herbs and food, as without food they will not be able to live, and assuming that they don't need to eat as we do right now is not correct.
     Another possible extension of such a simulation would be to make the foxes move more steps if they wish, because in reality the rabbits have much less mobility when compared with the foxes who can easily catch up to them. Therefore it is unreasonable to assume that they both move at the same right, and changing that could help our simulations validity.

Sunday, 5 December 2010

Chapter 10 36-49


36
Using your latest version of the project (or the foxes-and-rabbits-V2 project in case you have not done all the exercises), move the canBreed() method from Fox and Rabbit to Animal and rewrite it as shown in code 10.8. Provide appropriate versions of getBreedingAge() in Fox and Rabbit. Are those changes sufficient to recompile the project? If not, what is missing from the Animal class?ced any new participant types.
 Done, I had to also much an abstract method which accesses the age variable in the subclasses as it is also not defined in the Animal class.
37
Move the incrementAge() method from Fox and Rabbit to Animal by providing an abstract getmaxAge() method in Animal and a concrete version in Fox and Rabbit.
 I now realized that I could move the age field into the superclass, and did so. I also had to change the incrementAge() method from being private to protected because the subclassese need access to it.
38
Can the breed() method be moved to Animal?

If so, make this change.
>
 Yes it is possible, here is some of the code, to show how I did it:

39
In the light of all the changes you have made to these three classes, reconsider the visibility of each method and make any changes you feel are appropriate.
 As I stated earlier, I already recognized the need for these methods to either be public or protected, and I made them protected as it seemed they weren't supposed to be public earlier.
40
Was is possible to make these changes without having any impact on any other classes in the project? If so, what does this suggest about the degrees of encapsulation and coupling that were present in the original version?
 Well, at times these changes could have had an indirect impact, but generally it is the same exact project, with a more sophisticated structure. This suggests that the degrees of encapsulation and coupling were large, and therefore each class or hierarchy of classes didn't necessarily affect the other classes.
41
Define a completely new type of animal for the simulation as a subclass of Animal. You will need to decide what sort of impact its existence will have on the existing animal types. For instance, your animal might compete with foxes as a predator on the rabbit population, or your animal might prey on foxes but not on rabbits. You will probably find that you need to experiment quite a lot with the configuration settings you use for it. You will need to modify the populate() method to have some of your animals created at the start of a simulation. You should also define a new color for your new animal class. You can find a list of pre-defined color names on the API page documenting the Color class in the java.awt package.
 Done. I defined a made up creature that I named "KillerMouse" which is a super animal. It breeds super-fast, but has a very late breeding age. It lives basically for eternity (2000 years). It also feeds off of foxes and rabbits. I was truly messing around, but It's really an interesting situation because they breed so late. Once they actually breed, however, it's like a plague.
42
Introduce the Actor class into your simulation. Rewrite the simulateOneStep() method in Simulator to use Actor instead of Animal. You can do this even if you have not introduced any new participant types.

Does the Simulator class compile? Or is there something else that is needed in the Actor class?
 I'm having serious compiling issues with this. After creating the actor class I tried changing the simulateOneStep() method, and now I might have permanently damaged the project....
43
Redefine the abstract class Actor in your project as an interface.

Does the simulation still compile?

Does it run?
 My guess is that it would work had I not had these compiling issues.
44
Are the fields in the following interface static fields or instance fields?

public interface Quiz
{
int CORRECT = 1;
int INCORRECT = 0;
...
}

What visibility do they have?
 The fields in the interface have a public, static, and final visibility. But they aren't instance fields, as this class is an interface and not a normal class, and therefore they aren't directly the fields of an instance or object.
45
What are the errors in the following interface?

public interface Monitor
{
private static final int THRESHOLD = 50;
public Monitor (int initial);
public int getThreshold()
{
return THRESHOLD;
}
...
}
 Firstly, an interface cannot use a private field, so the visibility for it must be changed, also the user shouldn't write the visibility as it is implied, and rather it won't compile with them, and lastly there shouldn't be a method body in getThreshold() as it is an abstract method.
46
Add a non-animal actor to the simulation. For instance, you could introduce a Hunter class with the following properties.

Hunters have no maximum age and neither feed nor breed. At each step in the simulation, a hunter moves to a random location anywhere in the field and fires a fixed number of shots into random target locations around the field. Any animal in one of the target locations is killed.

Place just a small number of hunters in the field at the start of the simulation. Do the hunters remain in the simulation throughout or do they ever disappear?

If they do disappear, why might that be, and does that represent realistic behavior?

What other classes required changing as a result of introducting hunters?

Is there a need to introduce further decoupling to the classes?
 Done, I made the hunter act like a fox when it evokes its act() method, in that it uses the same procedure to check, except I made the movement random.

The hunters remain in the simulation because I put no age limit or restriction with food level onto them.

I believe there is no longer a need to introduce further decoupling, this is far extended, in fact I believe some methods we used are simply redundant.
47
Which methods do ArrayList and LinkedList have that are not defined in the List interface?

Why do you think that these methods are not included in List?
  getFirst(), getLast(), removeRange(), and trimToSize() are methods not defined in the List interface. This is probably because they don't necessarily apply to other possible implementations of the List class, or maybe because they simply apply to ArrayList and LinkedList, while they don't necessarily apply to List.
48
Read the API description for the sort methods of the Collections class in the java.util package.

Which interfaces are mentioned in the descriptions?
 It mentions implementing the Comparable interface.
49
Investigate the Comparator interface.
Define a simple class that implements Comparator.
Create a collection containing objects of this class and sort the collection.
 Done, this was a fairly simple task, I just made use of subtraction with two integers x and y, and later checked if they are equal to another integer z.

Wednesday, 1 December 2010

Chapter 10 20-35


20
Identify the similarities and differences between the Fox and the Rabbit classes.
Make separate lists of the fields, methods and constructors, and distinguish between the class variables (static fields) and instance variables.

 They each have the isAlive boolean field, the age integer field, a location field, a breeding age, a max age, a breeding probability, and a MAX_LITTER_SIZE field, which is the same name, but used differently in each class. Their constructors are primarily the same, except the fox class has the food level component in its constructor. As for methods, they have many in common such as IsDead(), giveBirth(), setDead(), incrementAge(), breed(), canBreed(), setLocation(), and getLocation(). Their run() and hunt() methods are similar in the sense that they move the instance, but are different in their purpose.
21
Candidate methods to be placed in a superclass are those that are identical in all subclasses.
Which methods are truly identical in the Fox and Rabbit classes?
In reaching a conclusion, you might like to consider the effect of substituting the values of class variables into the bodies of the methods that use them.

 IsDead(), giveBirth(), setDead(), incrementAge(), breed(), canBreed(), setLocation(), and getLocation(). Those methods are absolutely identical as has been asked.
22
In the current version of the simulation, the values of all similarly named class variables are different.
If the two values of a particular class variable (BREEDING_AGE, say) were identical, would it make any difference to your assessment of which methods are identical?

 No because the class variable would still be the same. It would still serve the same purpose, and would have the same functionality, it will only produce different results with different actual parameters.
23
What sort of regression-testing strategey could you establish before undertaking the process of refactoring on the simulation?
Is this something that you could conveniently automate?

 What is regression testing?
24
Create the Animal superclass in your version of the project. Make the changes dicussed in the text. Ensure that the simulation works in a similar manner as before.
 I'm constantly getting this error, I've been working on fixing it for a while, but I don't seem to see why it doesn't work:

25
How has using inheritance improved the project so far?
Discuss.

 There was no need for the code duplication that we had in the classes of Rabbit and Fox, and as a result the project is now more simplified, easier to use, and takes up less space.
26
Although the body of the loop in Code 10.6 no longer deals with the Fox and Rabbit types, it still deals with the Animal type.
Why is it not possible for it to treat each object in the collection simply using the Object type?
 If it were to treat each object in the collection using the Object type, theoretically, it could place anything into the collection, as almost everything is a sub-class of the Object class (except for primitive types). As a result we could potentially get unexpected and unwanted results.
27
Is it necessary for a class with one or more abstract methods to be defined as abstract?

If you are not sure, experiment with the source of the Animal class in the foxes-and-rabbits-v2 project.
 No, having an abstract method simply means that it would be excluded from any instance of that type, and that it would have to be overridden by one of the classes sub-classes if it has any.
28
Is it possible for a class that has no abstract methods to be defined as abstract?

If you are not sure, change act() to be a concrete method in the Animal class by giving it a method body with no statements.
 Yes it is. Being abstract would mean that no instance could be made from the given class; however, since it would have no abstract methods no method would have to necessarily be overridden in its sub-classes. This also means that it would be a super-class for one or more sub-classes, as creating an abstract class at the end of the hierarchy would be wasted code, and effort, since no instance of or relating to the class could be created.
29
Could it ever make sense to define a class as abstract if it has no abstract methods? Discuss this.
 Yes it could, this is largely discussed above, but basically if a user simply doesn't want any objects being created from that class he would define it as abstract. This wouldn't necessarily mean that any methods would have to overridden as they would if the class had abstract methods.
30


31


32
Which of the other simulation classes do not need to be aware of whether they are specifically dealing with foxes or rabbits? Could they be rewritten to use the Animal class instead? Would there be any particular benefits in doing this?/P>
 The field and location classes can use the abstract class of Animal which would benefit the project by having less code duplication.
33
Review the overriding rules for methods and fields discussed in Chapter 9. Why are they particularly significant in our attempts to introduce inheritance into this application?
 They are significant because with the new idea of having abstract methods it is important to know how to override methods, because otherwise the subclasses of the abstract method's class will also unintentionally be made into abstract classes.
34
The changes made in this text section have removed the dependence (couplings) of the simulateOneStep() method to the Fox and Rabbit class. The Simulator class however, is still coupled to Fox and Rabbit, because these classes are referenced in the populate() method. There is no way to avoid this: when we create Animal instances, we have to specify exactly what kind of animal to create. This could be improved by splitting the Simulator into two classes: one class Simulator, which runs the simulation and is completely decoupled from the concrete animal classes, and one class, PopulationGenerator (created and called by the simulator), which create the population. Only this class is coupled to the concrete animal classes, making it easier for a maintenance programmer to find places where change is necessary when the application is extended. Try implementing this refactoring step. The PopulationGenerator class should also define the colors for each type of animal.>
 Done, however, I can't see the purpose of this:
35
The canBreed() method of Fox and Rabbit are textually identical, yet we chose not to move them to the Animal class. Why is this? Try moving the methods from Fox and Rabbit and making them protected. Is there any way to make the resulting classes compile and, even if there is, does the resulting simulation work as it should? How can you tell?
 No, because each class has its own value for the BreedingAge, field and moving it up would require one to be set for the Animal class even though the fox and rabbit breeding ages are not the same. Since there is no way to have a universal BreedingAge, since that would defeat the purpose of the simulation, it is safe to assume that the canBreed() method cannot be moved up in the hierarchy.

Monday, 29 November 2010

Chapter 10 1-19


1
Create a Simulator object using the constructor without parameters and you should see the initial state of the simulation as shown in text Figure 10.2. The more numerous rectangles represent  the rabbits.
Does the number of foxes change if you call the simulateOneStep() method just once?

 Yes, it changed from 52 to 94.
2
Does the number of foxes change on every step?
What natural processes do you think we are modelling that cause the number of foxes to increase or decrease?

 Were modelling reproduction (rate), since in each step, the foxes reproduce by an amount.
3
Call the simulate() method to run the simulation continuously for for a significant number of steps, such as 50 or 100.
Do the numbers of foxes and rabbits increase of decrease at similar rates?

 No they don't, it seems pretty random. This is probably the purpose of such simulations as they aren't intended to be fixed, but random such as nature.
4
What changes do you notice if you run the simulation for a very long time, say 500 steps?
You can use the runLongSimulation() method to do this.

 All the foxes seemed to die out, this is probably due to their death rate increasing as their population was too big to support all the wolves, and there weren't enough rabits.
5
Use the reset() method to restore the starting state of the simulation, and then run it again.
Is an identical simulation run this time?
If not, do you see broadly similar patterns emerging anyway?

 The pattern is that at some point one of the population will die out, which portrays many natural actions.
6
If you run a simulation for long enough, do all the foxes, or all the rabbits ever die off completely?
If so, can you pinpoint any reasons why that might be occuring?

All the foxes will die if the rabbits die off, but the rabbits won't necessarily die if the foxes do. This is because foxes need rabbits to survive, but rabbits don't need foxes.
7
Do you feel that omitting gender as an attribute in the Rabbit class is likely to lead to an inaccurate simulation?
 Yes, because if we are going to consider the breeding factor of rabbits it is highly important to consider which rabbits can breed and which can't. Since in most organisms that have gender males and females are each about 50% of the population, it is safe to conclude that it is wrong to assume 100% of rabbits can breed when only 50% actually have the ability.
8
Are there other simplifications that you feel are present in our implementation of the Rabbit class, compared with real life?
Do you feel that these could have a significant impact on the accuracy of the simulation?

 I believe it is wrong to allow rabbits to move just as much as wolves, as in reality, wolves are much much faster and far more skilled at hunting rabbits than what is currently presented. This can have a significant impact because were assuming rabbits can just keep running away from wolves when really they would almost all be hunted if wolves and rabbits did not have the same amount of spaces to move.
9
Experiment with the effects of altering some or all of the values of the static variables in the Rabbit class.
For instance, what effect does it have on the fox and rabbit populations if the breeding probability of rabbits is much higher or lower?

 If the probability is increased then the wolves likewise reproduce more, as there is enough food for them all; however, over time they will reproduce so much that they will cause the rabbit race to extinct and will all starve. On the other hand, if the breeding probability is lowered then the rabbits don't reproduce enough, and the wolves become extinct due to starvation.
10
As you did for rabbits, assess the degree to which we have simplified the model of foxes and evaluate whether you feel the simplifications are likely to lead to an inaccurate simulation.
 As I mentioned earlier, I believe foxes should have a much larger span for their hunt method, as it is inaccurate to assume that wolves and rabbits have the same capability of hunting and running away. The wolf really should be far more superior in it's moving method.
11
Does increasing the maximum age for foxes lead to significantly higher numbers of foxes throughout the simulation, or is the rabbit population more likely to be reduced to zero as a result?
 Both are true to some extent. While increasing the maximum age of a wolf does increase the population of wolves, it also reduces the population of rabbits, eventually to zero, and causes a decrease in wolf numbers. The amount to which one increases this value only determines how fast this procedure occurs.
12
Experiment with different combinations of settings (breeding age, maximum age, breeding probability, litter size, etc.) for foxes and rabbits.
Do species always disappear completely in some configurations?
Are there configurations that are stable?

 All values can lead to the ending of species; it just depends on the extremities. If you increase or decrease any one value to an extremely high or low value this will eventually lead to the extinction of a race. Configurations that are stable are generally the ones that we started with, although the wolf default age is substantially higher than that of the rabbit and usually leads to the rabbits dying before the wolves.
13
Experiment with different sizes of field. (You can do this by using the second simulator constructor.)
Does the size of the field effect the likelihood of the species surviving?

 Yes it does, larger fields increase the likelihood of species surviving and inscrease the stability of the simulation, while small fields usually cause each of the species to die off after one runLongSimulation() method.
14
Currently a fox will eat at most one rabbit at each step. Modify the findFood() method so that rabbits in all adjacent locations are eaten at a single step.
Assess the impact of this change on the results of the simulation.

 Done, this simply causes the procedure to happen faster, the rabbits die faster, and consequently the wolves die of starvation. In many cases; however, a few rabbits remained alive but were simply too far from the wolves to be eaten and the wolves died off.
15
When a fox eats a large number of rabbits at a single step, there are several different possibilities as to how we can model its food level. If we add all the rabbit's food values the fox will have a very high food level, making it unlikely to die from hunger for a very long time.
Alternatively, we could impose a ceiling on the fox's foodlevel. This models the effect of a predator that kills prey regardless of whether it is hungry or not.
Assess the impacts of implementing this choice on the resulting simulation.

 All this would change is the time for the rabbits to die off, since the wolves will still be eating more rabbits since the first model of the project, but will only be limited by a food level. In the end the rabbits will get eaten off too fast and the wolves would die of starvation.
16
Modify the populate() method of Simulator to determine whether not setting an initail random age for foxes and rabbits is catastophic.
 Unsure how to modify this, but I'm assuming that not setting a random age is catastrophic as it is ignoring the fact that rabbits can only reproduce at a certain age, and would die too fast in the first few steps.
17
If an initail random age is set for rabbits but not for foxes, the rabbit population will tend to grow large, while the fox population remains very small.
Once the foxes do become old enough to breed, does the simulation tend to behave again like the original version?
What does this suggest about the relative sizes of the initial populations and their impact on the outcome of the simulation?

 This would probably not affect the simulation much, but will provide a more stable lifestyle for the wolves, as there would be many rabbits to eat once they can breed. This suggests that the population of wolves is generally smaller than that of the rabbits, however, not setting a random age for wolves is obviously not the real case and should not be the solution to creating a more stable environment.
18
When a rabbit moves to a free location, it is placed in the updated field only if there is not already a fox at that location.
What is the effect on the fox population if this constraint is removed?
Is the same constraint placed upon newly born rabbits?

 This effect is placed upon newly born rabbits as there is nothing declaring that it can't be. The effect on the fox population is that sometimes a rabbit will get passed a fox by moving onto the same location and will eventually cause hunting to be harder and will cause more foxes to die.
19
Could two foxes ever try to move to the same location in the updated field?
If so, should an attempt be made to avoid this situation?

 Yes they could, and while this should not be avoided, there should be a way for them to share the rabbits that they'd both hunt. Currently the first fox to move as the loop is executing will get all the rabbits and the second will get none. This is unrealistic, and should be dealt with.

Monday, 22 November 2010

Chapter Nine Test



1. Create a new class Faculty that extends class Person. Faculty members belong to departments, and teach courses. Provide appropriate fields and methods to make this class functional.

The following are the codes of my FacultyMember and Department classes:
 

import java.util.ArrayList;
/**
 * Write a description of class Department here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class Department
{
    private ArrayList members;

    /**
     * Constructor for objects of class Department
     */
    public Department()
    {
        members = new ArrayList <FacultyMember> ();
    }

    /**
     * An example of a method - replace this comment with your own
     *
     * @param  y   a sample parameter for a method
     * @return     the sum of x and y
     */
    public void addMember(FacultyMember teacher)
    {
        members.add(teacher);
    }
}


/**
 * Write a description of class FacultyMember here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class FacultyMember extends Person
{
    private Course course;
   
    /**
     * Constructor for objects of class FacultyMember
     */
    public FacultyMember(String initName, boolean gender, Course courseToTeach, String course1)
   {
    super(initName, gender);
    course = courseToTeach;
    }
   
    public String getCourse()
    {
        return course.getCourseTitle();
    }
   
    public void setCourse(Course newCourse)
    {
        course = newCourse;
    }
}

2. The Car Park is modeled by class CarPark. CarPark is a collection of parking spaces, which are modeled by class ParkingSpace. Continue to develop the project so that both faculty and students can be allocated parking spaces, and these parking spaces can be stored in the car park.

To do this I modified my CarPark class in order to make it compatible with all the above tasks. Here is its code:

/**
 * CarPark models a car park where the parking spaces are allocated
 *
 * @author (fdaly)
 * @version (version 1: nov 2007)
 */
public class CarPark
{
    private ParkingPlace[] parkingSpots;
   
    public CarPark(int size)
    {
        parkingSpots = new  ParkingPlace[size];
    }
   
    public void addSpot(ParkingPlace spot)
    {
        if(spot.getPlaceNumber() > parkingSpots.length)
             System.out.println("Please choose a parking spot that is anywhere between 0 and " + parkingSpots.length + ".");
        parkingSpots[spot.getPlaceNumber()] = spot;
    }
}

3. Develop a CarPark method that prints the names and car registration numbers of all allocated parking spaces. Use an overridden toString method in class ParkingSpace so that printing is simplified from class CarPark. Test your method with a car park that has spaces allocated for both faculty and students.

This was the result as asked (Mike is a Student instance, John is a FacultyMember instance):


4. Create a new class that will model a club. The club can have both faculty and student members. Create methods that permit you to add and to remove members from the club. Create a method that can print all male members or all female members of the club.

There is an issue with my BlueJ in that it won't compile the class. It simply freezes; however, I believe that this code is correct, apart from some syntactual mistakes which I cannot fix without the compiler:

import java.util.ArrayList;
/**
 * Write a description of class Club here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class Club
{
    private ArrayList clubMembers;
    /**
     * Constructor for objects of class Club
     */
    public Club()
    {
        clubMembers = new ArrayList <Person> ();
    }

    public void printClubDetails(boolean genderList) // true is male, false is female.
    {
        String gender = "";
        for(int i = 0; i<clubMembers.size(); i++)
        {
            if(genderList && clubMembers.get(i).isMale() == true)
            gender += "Male";
            System.out.println(clubMembers.get(i).getName() + gender);
            if(!genderList && clubMembers.get(i).isFemale() == true)
            gender += "Female";
            System.out.println(clubMembers.get(i).getName() + gender);
        }
    }
   
    public void removeMember(int MemberNumber)
    {
        clubMembers.remove(MemberNumber);
    }

    public void addMember(Person member)
    {
        clubMembers.add(member);
    }