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, 29 November 2010
Chapter 10 1-19
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);
}
Monday, 15 November 2010
CS Chapter 9.5-END
5 | Look up toString in the library documentation. What are its parameters? What is its return type? | Without being overriden, the toString() method does not take any methods and returns a string consisting of a representation of the object. This can be called by almost any instance, given it's a subclass of the Object class. |
6 | .... You can easily try this out. Create an object of class Video in your project, and then invoke the toString() method from the Object submenu in the object's popup menu. | Done: I can't upload pictures for some reason, the buttons to upload just won't work, I'll show you the issue tomorrow. |
7 | The version of print() shown in Code 9.1 produces the output shown in text figure 9.9. Reorder the staements in the method in your version of the DoME project so that it prints the details as shown in text Figure 9.10. | Done: |
8 | Having to use a superclass call in print() is somewhat restrictive in the ways we can format the output, because it is dependent on the way the superclass formats its fields. Make any necessary changes to the Item class and to the print() method of CD so that it produces the output shown in text Figure 9.11. Any changes you make to the Item class should be visible only to its subclasses. Hint: You used to use protected fields to do this. | I had an issue with this, I received an error after the method got overused. I'll talk to you about it next class: |
9 | Implement a transporter room with inheritance in your version of the zuul project. | N/A Skipped Ch.7 |
10 | Discuss how inheritance could be used in the zuul project to implement a player and a monster class. | N/A |
11 | Could (or should) inheritance be used to create an inheritance relationship (super-, sub-, or sibling class) between a character in the game and an item? | N/A |
12 | Assume you see the following lines of code: Device dev = new Printer(); dev.getName(); Printer is a subclass of Device. Which of these classes must have a definition of method getName() for this code to compile? | The Device class must have a definition of the method getName(), however, the Printer class may have overrided the method, in which case the definition of the getName() method that will be used is the one in the Printer class. |
13 | In the same situation as in the previous exercise, if both classes have an implementation of method getName(), which one will be executed? | As explained above, the Printer's version of the getName() method will be executed if it was overrided. |
14 | Assume you write a class Student, which does not have a declared superclass. You do not write a toString() method. Consider the following lines of code. Student st = new Student(); String s = st.toString(); Will these lines compile? What exactly will happen when you try to execute? | There is no reason why it should not work, as the first instantiation line is of the same type, and the toString method, as defined in the Object class, is one of the inherited methods of the Student class as it is not a primitive class. These lines of code will assign the details of the st Student object to a string, s. |
15 | In the same situation as the previous exercise (class Student, no toString() method), will the following lines compile? Why? Student st = new Student(); System.out.println(st); | |
16 | Assume your class Student overrides toString() so that it returns the student's name. You now have a list of students. Will the following code compile? If not, why not? If yes, what will it print? Explain in detail what happens. Iterator it = myList.iterator(); while (it.hasNext()) { System.out.println(it.next()); } | Yes, it will compile, my only worry is that it's not calling the toString() method, and instead is simply printing a list of Student's names. This is obvious as there is no reference here whatsoever to any toString() method. |
17 | Write a few lines of code that result in a situation where a variable x has the static type T and the dynamic type D. | T x = new D(); D y = new D(); ArrayList list = new ArrayList <T> (); list.add(x); list.add(y); return list; |
Tuesday, 9 November 2010
Chapter 8 Test
a. Describe how you can use two different BankAccount objects (acc1 and acc2) on the BlueJ workbench to transfer funds from one account to the other.
I will describe this using my code which does this sort of transfering:
public void transferMoney(double amount, BankAccount from, BankAccount to)
{
from.withdraw(amount);
to.deposit(amount);
}
Essentially what this does, is it takes withdraws a certain amount from one BankAccount object and it deposts a certain amount in another, to act as though they transfered money.
b. Use the relationship between BankAccount class and GoldBankAccount class to describe how inheritance works in Java. As you write your description you should use the following terms in an appropriate way.
The relationship between BankAccount and GoldBankAccount deals with inheritance, in which BankAccount is the superclass of GoldBankAccount, and GoldBankAccount is the subclass of BankAccount. In an inheritance hierarchy, the BankAccount class would therefore appear above the GoldBankAccount class. In the superclass constructor, the fields important to it, and GoldBankAccount are found. Therefore, there is no need to reuse those fields, or recreate them in the subtypes of the superclass, that would simply defeat the purpose of inheritance. Another feature of this inheritance relationship is that we can create a BankAccount Object and assign a subtype with subtype variables to it.
c. A Bank class would store all the accounts held by a bank. The data structure that holds these accounts is a single ArrayList. How is it that a single ArrayList can store objects of different types (BankAccount, and GoldBankAccount)?
It can store objects of type BankAccount which include all subtypes, such as GoldBankAccount. Therefore it can store them both.
d. Implement the Bank class to include a method that computes the total of all the balances held by the bank.
Done:
import java.util.ArrayList;
/**
* Write a description of class Bank here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Bank
{
// instance variables - replace the example below with your own
private ArrayList banks;
/**
* Constructor for objects of class Bank
*/
public Bank()
{
banks = new ArrayList <BankAccount> ();
}
public void addBankAccount(BankAccount object)
{
banks.add(object);
}
public int amountOfBanks()
{
return banks.size();
}
}
e. Why are are wrapper classes necessary in Java?
Because otherwise we couldn't be able to use primitive types in ArrayLists, as ArrayLists can only hold objects, but int and boolean, for example, aren't necessarily objects. Therefore there are wrapper classes for those classes, so they can be used in ArrayLists.
For those of you who work quickly..
(I will finish this later)
Create two new classes: JuniorGoldAccount, which is a more restrictive version of the GoldAccount class, and PlatinumAccount, which offers even more advantages than the GoldAccount.
Test your classes and include the code in this document
I will describe this using my code which does this sort of transfering:
public void transferMoney(double amount, BankAccount from, BankAccount to)
{
from.withdraw(amount);
to.deposit(amount);
}
Essentially what this does, is it takes withdraws a certain amount from one BankAccount object and it deposts a certain amount in another, to act as though they transfered money.
b. Use the relationship between BankAccount class and GoldBankAccount class to describe how inheritance works in Java. As you write your description you should use the following terms in an appropriate way.
The relationship between BankAccount and GoldBankAccount deals with inheritance, in which BankAccount is the superclass of GoldBankAccount, and GoldBankAccount is the subclass of BankAccount. In an inheritance hierarchy, the BankAccount class would therefore appear above the GoldBankAccount class. In the superclass constructor, the fields important to it, and GoldBankAccount are found. Therefore, there is no need to reuse those fields, or recreate them in the subtypes of the superclass, that would simply defeat the purpose of inheritance. Another feature of this inheritance relationship is that we can create a BankAccount Object and assign a subtype with subtype variables to it.
c. A Bank class would store all the accounts held by a bank. The data structure that holds these accounts is a single ArrayList. How is it that a single ArrayList can store objects of different types (BankAccount, and GoldBankAccount)?
It can store objects of type BankAccount which include all subtypes, such as GoldBankAccount. Therefore it can store them both.
d. Implement the Bank class to include a method that computes the total of all the balances held by the bank.
Done:
import java.util.ArrayList;
/**
* Write a description of class Bank here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Bank
{
// instance variables - replace the example below with your own
private ArrayList banks;
/**
* Constructor for objects of class Bank
*/
public Bank()
{
banks = new ArrayList <BankAccount> ();
}
public void addBankAccount(BankAccount object)
{
banks.add(object);
}
public int amountOfBanks()
{
return banks.size();
}
}
e. Why are are wrapper classes necessary in Java?
Because otherwise we couldn't be able to use primitive types in ArrayLists, as ArrayLists can only hold objects, but int and boolean, for example, aren't necessarily objects. Therefore there are wrapper classes for those classes, so they can be used in ArrayLists.
For those of you who work quickly..
(I will finish this later)
Create two new classes: JuniorGoldAccount, which is a more restrictive version of the GoldAccount class, and PlatinumAccount, which offers even more advantages than the GoldAccount.
Test your classes and include the code in this document
Monday, 8 November 2010
CS Chapter 9: 9.1-9.4
1 | Open your last version of the DoME project. Remove the print() method from class Item and move it into the Video and CD classes. Compile. What do you observe? | There is a compilation error since the title field belongs to the Item class from which we moved the method. |
2 | In your DoME project, add a print() method in class Item again. For now write the method body with a single statement that prints out only the title. Then modify the print() methods in CD and Video so that the CD version prints out only the artist and the Video version prints only the director. This removes the other errors ecountered above. You should now have a situation coressponding to figure 9.4 in the text, with print() methods in three classes. Compile your project. This design should work, if there are errors remove them. Before executing, predict which of the print() methods will get called if you execute the Database list() method. Try it out: Enter a CD and a video into the database and call the Database list() method. Which print() methods were executed? Was your prediction correct? Try to explain your observations. | Prediction: When executing the database print method, it will use the specific CD and Video print methods which will print out only either the artist or director, since we've overloaded the method in the sub-classes. My prediction was correct. |
3 | Modify your latest version of the DoME project to include the super call in the print() method. Test it. Does it behave as expected? Do you see any problems with this solution? | Yes it works, no problems: |
4 | Change the format of the output so that it prints the string "CD: " or Video: " (depending on the type of item) in front of the details. | Done: |
Thursday, 4 November 2010
Chapter 8 8.7-End
7 | Open the dome-v2 project. Add a class for video games to the project. Create some video game objects and test that all the methods work as expected. | Done, here are the class' fields: |
8 | Order these items into an inheritance hierarchy: apple, ice cream, bread, fruit, food-item, cereal, orange, dessert, chocolate mousse, baguette. | Done: |
9 | In what inheritance relationship might a touch pad and a mouse be? | Computer Devices |
10 | | Rectangle would be the parent class of square, as a square is a rectangle, but a rectangle is not a square, simply that. |
11 | Assume we have four classes: Person, Student, Teacher & PhDStudent. Teacher and Student are both subclasses of Person. PhDStudent is a subclass of Student. Which of the following assignments are legal and why? Person p1 = new Student(); Person p2 = new PhDStudent(); PhDStudent phd1 = new Student(); Teacher t1 = new Person(); Student s1 = new PhDStudent(); s1 = p1; s1 = p2; p1 = s1; t1 = s1; s1= phd1; phd1 = s1; | a) legal b) legal e) legal g) legal h) legal j) legal k) legal because sub-types can be assigned to super classes, or to their own class, but super classes can't be assigned to sub-classes, it's like saying a square gets new rectangle, it's preposterous. |
12 | Test your answers to the previous question by creating the classes mentioned in that exercise, and trying it out in BlueJ. | Done, this is the set up i used: |
13 | What has to change in the Database class when another item subclass (for example class VideoGame) is added? Why? | Nothing, because VideoGame is an Item, and therefore Item will allow VideoGame to be added to the ArrayList of Database without further coding. |
14 | Use the documentation of the standard class libraries to find out about the inheritance hierarchy of the collection classes. Draw a diagram showing the hierarchy. | Unable to find the section on standard class libraries. |
15 | Go back to the lab-classess project from chapter 1. Add instructors to the project. Use inheritance to avoid code duplication between students and instructors. | I attempted to add some methods to the project as well but received some compiling errors: |
16 | Draw an inheritance hierarchy representing parts of a computer system (processor, memory, disk drive, CD drive, printer, scanner, keyboard, mouse, etc.) | |
17 | Look at the code below. You have four classes (O,X,T and M) and a variable of each of these. O o; X x; T t; M m; The following assignments are all legal. m = t; m = x; o = t; The following assignments are all illegal. o = m; o = x; x = o; What can you say about the relationships of these classes? | They have no relationships, therefore it makes no sense whatsoever to assign them to one another. |
18 | Draw an inheritance hierarchy of AbstractList and all its (direct and indirect) subclasses, as they are defined in the Java standard library. | Done: |
Subscribe to:
Posts (Atom)