Exercise 1.3. Use a negative parameter value to move left, e.g Exercise 1.9. The House Picture. The main building:

Size: px
Start display at page:

Download "Exercise 1.3. Use a negative parameter value to move left, e.g Exercise 1.9. The House Picture. The main building:"

Transcription

1 Exercise 1.3 Use a negative parameter value to move left, e.g. -70 Exercise 1.9 The House Picture The main building: Create a new Square object Invoke its method makevisible() Make the square bigger by invoking the method changesize(newsize) (100 is a good size) Move the square down by invoking the method movevertical(distance) (again 80 is a good value) The window: Create a new Square object. Invoke its method makevisible() Change its color by invoking changecolor() write "black" in the popupwindow Move the square down by invoking the method movevertical(distance) (100 is a good value) Move it to the right by invoking moveright() The roof: Create a new triangle object. Invoke its method makevisible() Change its size with changesize(newheight, newwidth) (50,140) movevertical(70) movehoizontal(60) The Sun: Create new Circle object. Invoke its method makevisible() Change its color by invoking changecolor() (write "yellow" in the popup window) Optionally change its size with changesize(60) Move it to the right by invoking movehorizontal(180) The Hilltop Picture The hill:

2 Create a new Circle object. Invoke its makevisible() method. Change its color by invoking changecolor (write green in the popup window) Change its size with changesize to something like Move it left with movehorizontal(-500). Move it down with movevertical(125). The sun: Create a Circle. Make it visible. Set its size to 30. Move it right by 150 pixels. Move it down by 50 pixels. The larger figure: Create a new Person object. Invoke its makevisible method. Change its size to something like 50 high and 25 wide. Move it left by 30 pixels and up by around 8. The smaller figure: The size should be around 40 by 20. Move it left by 3 pixels and down by 2. Exercise 1.14 It uses the objects of the classes Circle, Square and Triangle. It then moves these objects to the right places and changes the sizes and colors of the obejcts. Essentially calling the same methods as used in exercise 1.9 Exercise 1.16 Change: to be: sun.changecolor("yellow"); sun.changecolor("blue"); Note that this change should be made in both the draw() and setcolor() methods. Students often forget to do it in the latter. Illustrate the problem by drawing the picture, then calling setblackandwhite() then setcolor() the sun will have been changed to yellow, rather than blue, if the second change is not made.

3 Exercise 1.17 The second sun will need to be positioned somewhere different from the first sun to be visible. As with the previous exercise, it is common for students to miss the need to change the setcolor and setblackandwhite methods for compatibility with the addition. This is an earlier introduction to the need for regression testing! Exercise 1.18 After the line sun.makevisible() insert the following: sun.slowmovevertical(250); Compile the Picture class (Press compile in the editor window) Create instance of class Picture and invoke its draw() method. Exercise 1.19 Remove the line (if added in the previous exercise): slowmovevertical(250); Right below the last after the draw() method, add the sunset() method : * Animates the sunset. public void sunset() sun.slowmovevertical(250); Compile! And run it. Exercise 1.20 Define a new field: private Person person; Initialize and position them in the draw(): person = new Person(); person.changesize(80, 40); // Place them at ground level. person.movevertical(15); // Make sure they are to the right of the house to start. person.movehorizontal(200); Make them visible and move up to the house in sunset(): Exercise 1.22 person.makevisible(); // Walk up to the house. person.slowmovehorizontal(-150);

4 When calling the method getname(), the name of the student is displayed in a popup window. The name displayed is the one typed in when the object was created. Exercise 1.24 It shows the number of students in the LabClass which is zero. Exercise 1.31 Students looking these values up in the tutorial might not be able to readily identify that the integer types used here are int, as opposed to byte, short or long. Similarly, they may well suggest float rather than double for the final one. Be sure to point out that String always has an initial upper-case letter, because these subtleties are often missed. 0 int "hello" String 101 int -1 int true boolean "33" String double Exercise 1.32 First you would have to decide which type the field should have. String would be a good type to hold a name, so we add the following line to the source file of Circle: private String name; The above line could be placed after this line in the source code of the Circle class: private boolean isvisible; Exercise 1.33 public void send(string msg) The name msg is arbitrarily chosen. Exercise 1.34 public int average(int firstnumber, int secondnumber) Exercise 1.35 The book is an object because it is a specific instance of the Book class. Exercise 1.36 Yes, an object can belong to several classes. One of the more famous examples are

5 the platypus, which is both a mammal and egg-laying.

6 Exercise 2.2 Zero. Exercise 2.3 If too much money is inserted the machine takes it all - no refund. If there isn't enough money inserted, it still prints out the ticket. Exercise 2.5 It looks almost completely the same. Only the price on the ticket is different. Exercise 2.6 The outer part of the student class: public class Student The outer part of the LabClass class: public class LabClass Exercise 2.7 Yes, the order of public and class matters. Exercise 2.8 It is possible to leave out the word public. Exercise 2.9 It is not possible to leave out the word class. Exercise 2.10 Fields: price balance total Constructors: TicketMachine Methods:

7 getprice getbalance insertmoney printticket Exercise 2.11 It does not have any return type. The name of the constructor is the same as the name of the class. Exercise 2.12 int Student Server Exercise 2.13 alive tutor game Exercise 2.14 Student, Server, Person and Game Exercise 2.15 The exact order matters. Exercise 2.16 Yes, it always necessary to have a semicolon after a field declaration. Exercise 2.17 private int status; Exercise 2.18 It belongs to the class Student. Exercise 2.19 It has two parameters. One is of type String and the other of type double. Exercise 2.20 It would be reasonable to expect the types to be the same as the two parameters (String and double). Can't really assume anything about the names, but probably something like title and

8 price. Exercise 2.21 name = petsname; Exercise 2.22 public Date(String month, int day, int year) Exercise 2.23 Aside from their names, the only difference is that getprice() returns the value of the price field whereas getbalance() returns the value of the balance field. Exercise 2.24 How much money have I inserted into the machine? Exercise 2.25 No. There is no direct link between the name of a method and the name of the field. However, it is a convention to use a name for the method that clearly links it to the field. Exercise 2.26 public int gettotal() return total; Exercise 2.27 Missing return statement. Exercise 2.28 The header for getprice() has an int as return type. The header for printticket() has void as return type. Exercise 2.29 No. Because they don't need to return anything. Yes. Both headers have void as return types. Exercise 2.31 It has a return type (void) and constructors do not have return types. It also does not have the same name as the class it is in. Exercise 2.32

9 price = cost; Exercise 2.33 score = score + points; Exercise 2.34 It is a mutator. Use an inspector to view the current score, then call the increase method with a positive parameter value and observe that score increases by that value. Alternatively, if score has an accessor method; call the accessor, then call increase, and then call the accessor once again to verify that it returns the updated value, indicating that the field has been modified. Exercise 2.35 price = price - amount; Exercise 2.36 Note that no quote marks are printed, just the following: My cat has green eyes. Exercise 2.37 public void prompt() System.out.println("Please insert the correct amount of money."); Exercise 2.38 Instead of printing out the actual price of the ticket, it displays the word "price": # price cents. Exercise 2.39 Prints out the exact same string as in exercise 2.38 Exercise 2.40 No, because neither uses the value of the price field in the println statement. Exercise 2.41 public void showprice() System.out.println("The price of a ticket is " + price + " cents."); Exercise 2.42

10 They display different prices. This is because each ticket machine object has its own price field. The price that was set in one ticket machine does not affect the other ticket machine s price. The unique value of each ticket machine's price field is substituted into the println statement when the method is called. Exercise 2.43 public TicketMachine() price = 1000; balance = 0; total = 0; When constructing a TicketMaching object you will not be prompted for a parameter value. The tickets always have a price of 1000 cents. Exercise 2.44 public TicketMachine() price = 1000; balance = 0; total = 0; public TicketMachine(int ticketcost) price = ticketcost; balance = 0; total = 0; Exercise 2.45 public void empty() total = 0; It needs no parameters. It is a mutator. Exercise 2.46 The balance does not change when an error message is printed. Inserting zero results in an error message. Exercise 2.47 This version does not print an error message when zero is inserted. Othere than that, it does not change the observable behavior of the method.

11 Exercise 2.48 Note the importance of using <= rather than < in the rewritten condition. if(amount <= 0) System.out.println("Use a positive amount rather than: " + amount); else balance = balance + amount; Exercise 2.49 The field is: isvisible. It determines whether the circle was visible or not. Yes. As circle is either visible or not, only two states (values) are needed. Exercise 2.50 In the printticket method of Code 2.8 the total is increased only by the price of the ticket, and not the full balance. The balance is then decreased by the price. Exercise 2.51 The else and associated block can be removed if statements do not have to have an else part. If an illegal amount is used, no error message is printed but the method otherwise works correctly. Exercise 2.52 It could never become negative. The value in balance is checked in printticket to ensure that it is always at least as large as price, so when price is subtracted balance cannot become negative. Exercise 2.54 saving = price * discount; Exercise 2.55 mean = total / count; Exercise 2.56 if(price > budget) System.out.println("Too expensive."); else System.out.println("Just right."); Exercise 2.57 if(price > budget) System.out.println("Too expensive. Your budget is only: " + budget);

12 else System.out.println("Just right."); Exercise 2.58 Because balance is set to zero and then this new value is returned rather than the old one. The method will always return zero. It can be tested by inserting an amount, and then calling refundbalance(). The original would then return the amount inserted, but the new method returns 0. Exercise 2.59 An error is printed: unreachable statement. A return statement ends (exits) the method. Code after a return statement can therefore never be executed. Exercise 2.60 The variable price is being re-declared as a local variable in the constructor this is the effect of the word int in front of it. This local variable hides the field of the same name. So the ticket price is never assigned to the price field. Exercise 2.61 public int emptymachine() int oldtotal = total; total = 0; return oldtotal; Exercise 2.62 public void printticket() int amountlefttopay = price - balance; if(amountlefttopay <= 0) // Simulate the printing of a ticket. System.out.println("##################"); System.out.println("# The BlueJ Line"); System.out.println("# Ticket"); System.out.println("# " + price + " cents."); System.out.println("##################"); System.out.println(); // Update the total collected with the price. total += price; // Reduce the balance by the prince. balance -= price; else System.out.println("You must insert at least: " + amountlefttopay + " more cents."); Exercise 2.63

13 You would need fields to store the prices of each of the tickets that the machine can issue. You would need a method to select which type of ticket you would want. It will not be necessary to modify many of the existing methods, if the price field is updated each time you select a new ticket type. You would probably need to modify the constructor, to allow several ticket prices. Exercise 2.64 Name: getcode Return type: String Exercise 2.65 Name: setcredits Parameter name: creditvalue Parameter type: int Exercise 2.66 public class Person Exercise 2.67 private String name; private int age; private String code; private int credits; Exercise 2.68 public Module(String modulecode) code = modulecode; Exercise 2.69 public Person(String myname, int myage) name = myname; age = myage; Exercise 2.70 The return type should not be void. public int getage()

14 return age; Exercise 2.71 public String getname() return name; Exercise 2.72 public void setage(int newage) age = newage; Exercise 2.73 public void printdetails() System.out.println("The name of this person is " + name); Exercise 2.74 student1 : Student name: Benjamin Johnson id: credits: 0 Exercise 2.75 "Henr557" Exercise 2.76 It opens the editor with the source code for the Student class. It displays a message: StringIndexOutOfBoundsException This happens because the method getloginname expects the name to be at least 4 characters long and "djb" is only 3 characters. Exercise 2.77 public Student(String fullname, String studentid) if(fullname.length() < 4) System.out.println("Error! The name should be at least 4 characters long"); if(studentid.length() < 3) System.out.println("Error! The studentid should be at least 3 characters long"); name = fullname; id = studentid;

15 credits = 0; Exercise 2.78 public String getloginname() String loginnamepart; if(name.length() < 4) loginnamepart = name; else loginnamepart = name.substring(0,4); String loginidpart; if(id.length() < 3) loginidpart = id; else loginidpart = id.substring(0,3); return loginnamepart + loginidpart ; Exercise "catfish" "cat9" "12cat" "cat39" "f" StringIndexOutOfBoundsException Exercise 2.80 The first call returns 0 and the second returns 500. Exercise 2.81 Because t2 refers to the same object as t1, the call will print 500. This example of aliasing is an important one and students should try to ensure that they understand what is going on here. Exercise 2.82 The call returns Even though the change was made via t1, because t2 is referring to the same object, it sees the new value. Note that we have only created a single TicketMachine object in these two exercises, but two variables refer to that one object. Exercise 2.83 * Returns the author of this book. public String getauthor()

16 return author; * Returns the title of this book. public String gettitle() return title; Exercise 2.84 * Prints the name of the author in the terminal window. public void printauthor() System.out.println("Author: " + author); * Prints the title of the book in the terminal window. public void printtitle() System.out.println("Title: " + title); Exercise 2.85 Delete the constructor and insert this: private int pages; * Set the author and title fields when this object * is constructed. public Book(String bookauthor, String booktitle, int bookpages) author = bookauthor; title = booktitle; pages = bookpages; * Returns the number of pages in this book. public int getpages() return pages; Exercise 2.86? The objects are immutable because the class contains no methods to change the values of any of the fields once an instance has been created. Exercise 2.87? public void printdetails()

17 System.out.print ("Title: " + title + ", "); System.out.print("Author: " + author + ", "); System.out.println("Pages: " + pages); Exercise 2.88 Delete the constructor and insert: private String refnumber; * Set the author and title fields when this object * is constructed. public Book(String bookauthor, String booktitle, int bookpages) author = bookauthor; title = booktitle; pages = bookpages; refnumber = ""; * Sets the reference number for this book public void setrefnumber(string ref) refnumber = ref; * Gets the reference number for this book public String getrefnumber() return refnumber; Exercise 2.89 public void printdetails() System.out.println("Title: " + title); System.out.println("Author: " + author); System.out.println("Pages: " + pages); String refnumberstring; if(refnumber.length() > 0 ) refnumberstring = refnumber; else refnumberstring = "ZZZ"; System.out.println("Reference number: " + refnumberstring);

18 Exercise 2.90 public void setrefnumber(string ref) if(ref.length() >= 3) refnumber = ref; else System.out.println("Error! The reference number must be at least 3 characters long."); Exercise 2.91 Add the field: private int borrowed; Add the methods: * Borrows the book. Increments the number of times the book has been borrowed. public void borrow() borrowed++; * Gets the number of times the book has been borrowed. public int getborrowed() return borrowed; Add this line to printdetails method: System.out.println("Borrowed: " + borrowed); Exercise 2.92? private boolean coursetext; public boolean iscoursetext() return coursetext; Exercise 2.93 public class Heater private int temperature; * Creates a new Heater with an initial temperature of 15.

19 public Heater() temperature = 15; * Increases the temperature by 5 degrees public void warmer() temperature += 5; * Decreases the temperature by 5 degrees public void cooler() temperature -= 5; * Gets the current temperature of the heater public int gettemperature() return temperature; Exercise 2.94 public class Heater private int temperature; private int min; private int max; private int increment; * Creates a new Heater with an initial temperature of 15. public Heater(int minimum, int maximum) min = minimum; max = maximum; temperature = 15; increment = 5; * Increases the temperature public void warmer() int newtemperature = temperature + increment; if(newtemperature <= max) temperature = newtemperature;

20 * Decreases the temperature public void cooler() int newtemperature = temperature - increment; if(newtemperature >= min) temperature = newtemperature; * Sets the increment, which determines how much the two methods * warmer() and cooler() changes the temperature. public void setincrement(int inc) if(inc >= 0) increment = inc; * Gets the current temperature of the heater public int gettemperature() return temperature; If the setincrement method does not check for negative values, and a negative value is passed, then the program will not work as expected. The minimum and maximum values can be exceeded.

21 Exercise 3.1 The class diagram contains only 2 elements: LabClass and Student. The LabClass class is linked to the Student class. The object diagram contains 4 elements. 1 LabClass object and 3 Student objects. The LabClass object contains links to the three Student objects. Exercise 3.2 A class diagram changes when you modify the source code. That can be by changing the relations between classes or creating/deleting classes. Exercise 3.3 An object diagram changes when the program is running. It can be changed by creating new objects, calling methods, and making assignments involving object references. Exercise 3.4 private Instructor tutor; Exercise 3.6 Nothing happens. No. It should print out an error message. Exercise 3.7 It would not allow a value of zero to be used as a replacement. Exercise 3.8 The test will be true if one of the conditions is true It will always be true if the limit is larger than or equal to 0. It would also be true if the replacement value is negative, for instance. Exercise 3.9 false true false false true Exercise 3.10

22 The long version of this would be: (a == true && b == true) (a == false && b == false) This can be simplified to: (a && b) (!a &&!b) But since both must have identical values, the simplest form is: a==b Exercise 3.11 As in the previous exercise, the long version would be: (a == true && b == false) (a == false && b == true) This can be simplied to: (a &&!b) (!a && b) Or: (a b) && (a!= b) Or even: a!= b Exercise 3.12!(!a!b) Exercise 3.13 No. The method assumes that the value will only contain two digits. Exercise 3.14 No. Exercise 3.15 The exact definition can be found in The Java Language Specification Third Edition in section The correct answer may not be intuitive when negative values are involved.

23 The key is that the modulus operator works so that (a / b) * b + (a % b) == a rearranging we get: a % b == a (a / b) * b which works even when negative values are involved. Exercise Exercise , -3, -2, -1, 0, 1, 2, 3, 4 Exercise 3.19 Values in the range from -(m-1) to (m-1) Exercise 3.20 As long as value is smaller than limit, it gets incremented by 1 (the modulo can be ignored) When value reaches the limit, the modulo operation will result in value being set to 0. So, the increment method increments value by one, until the limit is reached, at which point it will start over at 0. Exercise 3.21 Many students get this one wrong on the boundaries. A common wrong solution, which results in a value equal to the limit is: public void increment() if(value < limit) value = value + 1; else value = 0; A correct, but difficult to visually verify version, which is often the result of fixing the above is: public void increment() if(value < limit - 1) value = value + 1; else

24 value = 0; Best, because it is easy to see that it is correct is: public void increment() value = value + 1; if(value >= limit) value = 0; Both ways of incrementing are equally good. Once the modulus operator is understood, its use is obviously more succinct. Exercise 3.23 The time is initialized to The constructor creates two new NumberDisplay which are initialized to 0 (in the constructor for NumberDisplay) Exercise 3.24 It needs 60 clicks Using the method settime() on the object. Exercise 3.26 public Editor(String filename, int number) Exercise 3.27 Rectangle window = new Rectangle(3,6); Exercise 3.28 It initializes the time to the values passed to the method. It uses the method settime to set the time to the initial value. Exercise 3.29 Both constructors creates two new NumberDisplays. The first constructor calls updatedisplay and the second calls settime(hour, minute). In the second constructor there is no call to updatedisplay because this will be done in the method settime. Exercise 3.30 p1.print("file1.txt", true); p1.print("file2.txt", false);

25 int status; status = p1.getstatus(12); status = p1.getstatus(34); Exercise 3.31 and ) change the updatedisplay in ClockDisplay as this: * Update the internal string that represents the display. private void updatedisplay() int hour = hours.getvalue(); String suffix = "am"; if(hour >= 12) hour = hour - 12; suffix = "pm"; if(hour == 0) hour = 12; displaystring = hour + "." + minutes.getdisplayvalue() + suffix; 2) public ClockDisplay() hours = new NumberDisplay(12); //changed minutes = new NumberDisplay(60); updatedisplay(); public ClockDisplay(int hour, int minute) hours = new NumberDisplay(12); //changed minutes = new NumberDisplay(60); settime(hour, minute); private void updatedisplay() int hour = hours.getvalue(); if(hour == 0) hour = 12; displaystring = hour + "." + minutes.getdisplayvalue(); Exercise 3.38 Since the debugger shows that: Mailitem item = <object reference> This indicates that item is not null, and the next line that will be marked is item.print()

26 Exercise 3.39 This time the item is null. The if-statement will then execute the line: System.out.println("No new mail."); Exercise 3.40 After pressing Step Into and then pressing Step it prints: From: Sophie After the next Step it prints: To: Juan And after another Step: Message: Hi Juan! Step Into goes into the method print(). From there on, each line of print is executed by a pressing Step. This results in the lines being printed one at a time instead of just printing all 3 lines as before. Exercise 3.45 A subject field must be added to the MailItem class and set via the constructor. An accessor is also added and the print() method should include it. The MailClient s sendmailitem() method requires a parameter to receive the subject. See mail-system. Exercise 3.46 Screen screen = new Screen(1024, 768); if(screen.numberofpixels() > ) screen.clear(true);

27 Exercise 4.4 private ArrayList<Book> library; Exercise 4.5 ArrayList<Student> cs101; Exercise 4.6 private ArrayList<MusicTrack> tracks; Exercise 4.7 library = new ArrayList<Book>(); cs101 = new ArrayList<Student>(); tracks = new ArrayList<MusicTrack>(); with Java 7, these can be simplified to: library = new ArrayList<>(); cs101 = new ArrayList<>(); tracks = new ArrayList<>(); Exercise Exercise 4.9 items.get(4); Exercise Exercise 4.11 files.add(favoritetrack); Exercise 4.12 dates.remove(2); Exercise Exercise 4.14 public void checkindex(int index) if(index < 0 index >= files.size()) System.out.println("The valid range is 0 to " +

28 (files.size() 1)); If the collection is empty, there is no valid index and the error message will still appear. This special case could be catered for my a separate if statement that checks for an empty collection and prints an error message specific to that case. Exercise 4.15 The following are all valid. The first is in the spirit of the previous exercise. The second rewrites to the opposite form and the third gives the most concise representation. public boolean validindex(int index) if(index < 0 index >= files.size()) return false; else return true; public boolean validindex(int index) if(index >= 0 && index < files.size()) return true; else return false; public boolean validindex(int index) return index >= 0 && index < files.size(); Exercise 4.16 * List a file from the collection. index The index of the file to be listed. public void listfile(int index) if(validindex(index)) String filename = files.get(index); System.out.println(filename); * Remove a file from the collection. index The index of the file to be removed.

29 public void removefile(int index) if(validindex(index))) files.remove(index); Exercise 4.18 public void listallfiles() Exercise 4.19 No. We have no idea how many lines we would need. Exercise 4.24 * Show a list of all the files in the collection, * along with their index values. public void listallfiles() // A variable to keep track of the index position. int position = 0; for(string filename : files) System.out.println(position + ": " + filename); position++; Exercise 4.26 * List the names of files matching the given search string. * If none are found, print a message. searchstring The string to match. public void listmatching(string searchstring) // Assume that there will be no matches. boolean nomatch = true; for(string filename : files) if(filename.contains(searchstring)) System.out.println(filename); // We found at least one match. nomatch = false; if(nomatch) System.out.println("No files matched: " + searchstring);

30 Exercise 4.27 * Play a sample from all files matching the given search string. artist The string to match. public void playsamplesby(string artist) int position = 0; for(string filename : files) if(filename.contains(artist)) playandwait(position); position++; Exercise 4.28 for(track track : tracks) Exercise 4.29 boolean found = false; while(!found) if(the keys are in the next place) found = true; Exercise 4.30 public void multiplesoffive() int multiple = 10; while(multiple <= 95) System.out.println(multiple); multiple = multiple + 5; Exercise 4.31 int sum = 0; int num = 1; while(num <= 10) sum += num; num++; System.out.println("The sum of the values 1 to 10 is " + sum); Exercise 4.32 * Sum the numbers from a to b, inclusive.

31 public int sum(int a, int b) int sum = 0; int number = a; while(number <= b) sum = sum + number; number = number + 1; return sum; * A crude determination of whether n is prime or not. * More efficient methods are possible. public boolean isprime(int n) int divisor = 2; while(divisor < n ) if(n % divisor == 0) return false; divisor = divisor + 1; return true; Exercise 4.34 The value does not vary. public int findfirst(string searchstring) int index = 0; // Record that we will be searching until a match is found. boolean searching = true; int size = files.size(); while(searching && index < size) String filename = files.get(index); if(filename.contains(searchstring)) // A match. We can stop searching. searching = false; else // Move on. index++; if(searching) // We didn't find it. return -1; else // Return where it was found. return index;

32 Exercise 4.38 Add: stopplaying(); to playtrack() once the index has been validated. Exercise 4.39 * Remove tracks whose titles match the search string. * A partial match is used. title The string to be matched. public void removetitles(string title) Iterator<Track> it = tracks.iterator(); while(it.hasnext()) Track t = it.next(); if(t.gettitle().contains(title)) it.remove(); Exercise import java.util.arraylist; * Store details of club memberships. * (your name) (a version number or a date) public class Club private ArrayList<Membership> members; * Constructor for objects of class Club public Club() members = new ArrayList<Membership>(); * Add a new member to the club's list of members. member The member object to be added.

33 public void join(membership member) members.add(member); The number of members (Membership objects) in * the club. public int numberofmembers() return members.size(); Exercise 4.43 * Select and play a single random track. public void randomplay() if(tracks.size() > 0) Random rand = new Random(); int index = rand.nextint(tracks.size()); playtrack(index); Exercise 4.45 The Collections.shuffle() method offers a way to randomly order a collection. This is used in the first version, which does not require a separate random number generator: * Play all tracks once in a random order. public void randomplayall() ArrayList<Track> lefttoplay = new ArrayList<Track>(tracks); Collections.shuffle(leftToPlay); for(track t : lefttoplay) player.playsample(t.getfilename()); The second version makes a copy of the list and repeatedly removes a random track to be played until the list is empty. * Play all tracks once in a random order. public void randomplayall() Random rand = new Random(); ArrayList<Track> lefttoplay = new ArrayList<Track>(tracks);

34 while(lefttoplay.size() > 0) int index = rand.nextint(lefttoplay.size()); Track t = lefttoplay.remove(index); player.playsample(t.getfilename()); Exercise 4.47 boolean successful = selectedlot.bidfor(new Bid(bidder, value)); Exercise 4.48 public void close() for(lot lot : lots) System.out.println(lot.getNumber() + ": " + lot.getdescription()); // Include any details of a highest bid. Bid highestbid = lot.gethighestbid(); if(highestbid!= null) System.out.println(" Highest bidder: " + highestbid.getbidder().getname()); System.out.println(" Bid: " + highestbid.getvalue()); else System.out.println(" Not sold"); Exercise 4.49 * Returns a list of unsold lots public ArrayList<Lot> getunsold() ArrayList<Lot> unsoldlots = new ArrayList<Lot>(); for(lot lot : lots) Bid highestbid = lot.gethighestbid(); if(highestbid == null) unsoldlots.add(lot); return unsoldlots; Exercise 4.50 The getlot method assumes that a Lot is stored at location getlotnumber()-1 in its ArrayList. If lots can be removed then index numbers may be changed. The getlot method always checks for consistency so if there is an inconsistency the an error message is printed in the terminal window.

35 Exercise 4.51 * Return the lot with the given number. Return null * if a lot with this number does not exist. number The number of the lot to return. public Lot getlot(int number) Lot lot = null; if(lots.size() > 0) lot = lots(0); int nextindex = 1; while(lot.getnumber()!= number && nextindex < lots.size()) lot = lots.get(nextindex); nextindex++; if (lot == null lot.getnumber()!= number) System.out.println("Lot number: " + number + " does not exist."); return null; else return lot; Exercise 4.52 * Remove the lot with the given lot number. number The number of the lot to be removed The Lot with the given number, or null if * there is no such lot. public Lot removelot(int number) //First we find the lot with the given number Lot lot = getlot(number); if(lot!= null) //Then we can use the method remove with lot as argument lots.remove(lot); return lot; Exercise 4.53 LinkedList has these methods that ArrayList does not have: void addfirst(e o) void addlast(e o) E getfirst() E getlast() E removefirst()

36 E removelast() Where E refers to the type of item stored in the list. ArrayList has these methods that LinkedList does not have: void ensurecapacity(int mincapacity) void trimtosize() Exercise 4.54 * Determine the number of members who joined in the * given month month The month we are interested in. The number of members. public int joinedinmonth(int month) int count = 0; if(month < 1 month > 12) System.out.println("Month " + month + " out of range. " + "It must be in the range "); else for(membership member : members) if(member.getmonth() == month) count++; return count; Exercise 4.55 public ArrayList purge(int month, int year) ArrayList<Membership> purged = new ArrayList<Membership>(); if(month < 1 month > 12) System.out.println("Month " + month + " out of range. " + "It must be in the range "); else Iterator<Membership> it = members.iterator(); while(it.hasnext()) Membership member = it.next(); if(member.getmonth() == month && member.getyear() == year) // Must use the remove method from the iterator. // Check the documentation for the Iterator // for more info. it.remove(); purged.add(member);

37 return purged; Exercise 4.56 public void printproductdetails() for(product product : stock) System.out.println(product.toString()); Exercise 4.57 public Product findproduct(int id) for(product product : stock) if(product.getid() == id) return product; return null; Exercise 4.58 public int numberinstock(int id) Product product = findproduct(id); if(product!= null) return product.getquantity(); else return 0; Exercise 4.59 public void delivery(int id, int amount) Product product = findproduct(id); if(product!= null) product.increasequantity(amount); Exercise 4.60 * Print details of all the products which has stock * levels below the given amount public void printlowstockproducts(int upperlimit) for(product product : stock)

38 if(product.getquantity() < upperlimit) System.out.println(product.toString()); * Add a product to the list. item The item to be added. public void addproduct(product item) if(! stock.contains(item)) stock.add(item); * Try to find a product in the stock with the given name. The identified product, or null if there is none * with a matching name. public Product findproduct(string name) for(product product : stock) if(product.getname().equals(name)) return product; return null; Exercise 4.61 The busiest time of day: 18 Exercise 4.62 Person[] people; Exercise 4.63 boolean[] vacant; Exercise 4.65 int[] counts; boolean[] occupied = new boolean[5000]; Exercise 4.66 readings = new double[60]; urls = new String[90]; machines = new TicketMachine[5];

39 Exercise 4.67 None. It only creates an array to hold String objects. Exercise 4.68 The brackets must be square rather than round. double[] prices = new double[50] Exercise 4.69 It throws an ArrayIndexOutOfBoundsException: 24 Exercise 4.70 * Print the hourly counts. * These should have been set with a prior * call to analyzehourlydata. public void printhourlycounts() System.out.println("Hr: Count"); int hour = 0; while(hour < hourcounts.length) System.out.println(hour + ": " + hourcounts[hour]); hour++; Exercise 4.71 public void printgreater(double[] marks, double mean) for(int index = 0; index < marks.length; index++) if(marks[index] > mean) System.out.println(marks[index]); Exercise 4.72 * Create an object to analyze hourly web accesses. filename The file to be analyzed. public LogAnalyzer(String filename) // Create the array object to hold the hourly // access counts. hourcounts = new int[24]; // Create the reader to obtain the data. reader = new LogfileReader(filename);

40 Exercise 4.73 * Return the number of accesses recorded in the log file public int numberofaccesses() int total = 0; // Add the value in each element of hourcounts to total. for(int hourcount : hourcounts) total = total + hourcount; return total; Exercise 4.75 * Return the busiest hour of day public int busiesthour() int busiesthour = 0; for(int hour = 1; hour < hourcounts.length; hour++) if(hourcounts[hour] > hourcounts[busiesthour]) busiesthour = hour; return busiesthour; Exercise 4.76 * Return the quietest hour of day public int quietesthour() int quietesthour = 0; for(int hour = 1; hour < hourcounts.length; hour++) if(hourcounts[hour] < hourcounts[quietesthour]) quietesthour = hour; return quietesthour; Exercise 4.77 In the above implementation, it is the first one that is found. Exercise 4.78 * Return the two-hour period which is busiest. public int busiesttwohourperiod()

41 int busiestperiod = 0; int busiestperiodcount = 0; for(int hour = 0; hour < hourcounts.length - 1; hour++) int periodcount = hourcounts[hour] + hourcounts[hour+1]; if(periodcount > busiestperiodcount) busiestperiod = hour; busiestperiodcount = periodcount; return busiestperiod; Exercise 4.82 Reasons for choosing a fixed size array could be: Performance is slightly better. Not so good if students are added and removed from time to time. Reasons for keeping the dynamically sized list: No need to keep track of the current number of students. Good for future enhancements (for instance if we want to have a method to remove a student from the list). Exercise 4.83 * Show a list of all the files in the collection. public void listallfiles() for(int i = 0; i < files.size(); i++) System.out.println(files.get(i)); Exercise 4.84 A do-while loop only tests it condition after executing the statements in the loop s body at least once. The loop continues to execute while the condition is true, as with the while loop. int i = 1; do System.out.print(i + " "); i++; while(i <= 10); System.out.println(); Exercise 4.85 Solutions that use a do-while often end up including a duplicate of something close to the loop s condition inside the body of the loop, in order to avoid doing part of the

42 body one-too-many times. The do-while loop should be used sparingly, as it is rarely superior to iteration using a while loop. * Show a list of all the files in the collection. public void listallfiles() if(files.size() > 0) // There is at least one file. int i = 0; do System.out.println(files.get(i)); i++; while(i < files.size()); Exercise 4.86 * Find the index of the first file matching the given * search string. searchstring The string to match. The index of the first occurrence, or -1 if * no match is found. public int findfirst(string searchstring) int index = 0; // Record that we will be searching until a match is found. boolean searching = true; if(files.size() > 0) // There is at least one to check. do String filename = files.get(index); if(filename.contains(searchstring)) // A match. We can stop searching. searching = false; else // Move on. index++; while(searching && index < files.size()); if(searching) // We didn't find it. return -1; else // Return where it was found. return index;

43 Exercise 5.2 The documentation contains the following sections: Overall description of the class: its purpose and how to use it A brief summary of the fields A brief summary of the constructors A brief summary of the methods A detailed description of the fields A detailed description of the constructors A detailed description of the methods Exercise 5.3 Both check whether the string contains their first argument. The single-argument version of the method starts the match at index 0 within the string. The two-argument version starts the match at the position of the second argument. Both return true if there is a match and false otherwise. Exercise 5.4 Yes: public boolean endswith(string suffix) Exercise 5.5 Yes: public int length() Exercise 5.7 Signature: public String trim() Example: String trimmedtext = text.trim(); Exercise 5.8 add the line: input = input.trim(); to the start() method of SupportSystem Exercise 5.9 add the line: input = input.tolowercase();

44 to the start() method of SupportSystem Exercise 5.10 boolean Exercise 5.11 if(input.equals("bye")) finished = true; Exercise 5.12 Package: java.util It generates random numbers An instance is created by using one of the two constructors: Random random = new Random(); Random random = new Random(seed); To generate a random integer: random.nextint(); Exercise 5.13 Random random = new Random(); random.nextint(); Exercise 5.14 import java.util.random; public class RandomTester private Random random; // the random number generator public RandomTester() random = new Random(); public void printonerandom() System.out.println(random.nextInt()); public void printmultirandom(int howmany) for(int i = 0; i < howmany; i++) printonerandom();

45 Exercise ,1,2,...,99 Exercise 5.16 public int throwdice() return random.nextint(6) + 1; Exercise 5.17 public String getresponse() int answer = random.nextint(3); if(answer == 0) return "yes"; else if(answer == 1) return "no"; else return "maybe"; A more sophisticated alternative would be: public String getresponse() String[] responses = "yes", "no", "maybe", ; return responses[random.nextint(responses.length)]; Exercise 5.18 private ArrayList<String> responses; public RandomTester() // constructor responses = new ArrayList<String>(); responses.add("yes"); responses.add("don't know");... public String getresponse() return responses.get(random.nextint(responses.size())); Exercise 5.19 public int getonerandom(int max)

46 return random.nextint(max) + 1; Exercise 5.20 public int getonerandom(int min, int max) return random.nextint(max - min + 1) + min; public int getonerandom(int max) return getonerandom(1, max); Exercise 5.22 When you add more responses these also get shown randomly together with the existing ones. This is because the length of the list with responses is used when generating the random number. Exercise 5.24 Methods in HashMap that depend on the type parameters: Set<Map.Entry<K,V>> entryset() V get(object key) Set<K> keyset() V put(k key, V value) void putall(map<? extends K,? extends V> m) V remove(object key) Collection<V> values() Yes, the same type could be used for both parameters. Exercise 5.25 Call its size() method. Exercise 5.26 public class MapTester private HashMap<String, String> phonebook = new HashMap<String, String> (); public MapTester() phonebook.put("homer Jay Simpson", "(531) "); phonebook.put("charles Montgomery Burns", "(531) "); phonebook.put("apu Nahasapeemapetilon", "(531) "); public void enternumber(string name, String number)

47 phonebook.put(name, number); public String lookupnumber(string name) return phonebook.get(name); Exercise 5.27 It overwrites the previous value associated with the key. Exercise 5.28 Both values stay in the map. HashMaps only uses the key to distinguish entries - not the values. Exercise 5.29 phonebook.containskey("homer Jay Simpson"); Exercise 5.30 It returns null. Exercise 5.31 (duplicates 5.25) phonebook.size() Exercise 5.32 Call the keyset method to return the Set of keys, and then iterate over the set. for(string name : phonebook.keyset()) System.out.println(name); Exercise 5.34 Similarities between HashSet and ArrayList Both contains a collection of objects It is possible to add objects (with the add method) It is possible to remove objects (with the remove method) Both have a size() Both have provide an iterator() method to go through all the elements Differences: In a HashSet each object can only appear once in the set (because it is a Set). In a ArrayList an Object can appear multiple times. An ArrayList is ordered while a HashSet is not ordered.

48 Exercise 5.35 You can use regular expression to define how a string should be split. Some documentation on regular expressions in Java under the Pattern class in the java.util.regex package. Exercise 5.36 String[] words = s.split("[ \t]"); String[] words = s.split(":"); Exercise 5.37 Using HashSet guaranties that there are no duplicate elements, but it does not keep the order of the words. Exercise 5.38 It creates empty strings - which was probably not the intention. to fix it we could do this: String[] words = s.split("[ \t]+"); Exercise 5.39 import java.util.arrays; The Arrays class defines various sort methods: public void sortvalues(int[] values) Arrays.sort(values); for(int value : values) System.out.print(value + " "); System.out.println(); Exercise 5.40 See the modified start() method of SupportSystem in: Code 5.6 and the modified generateresponses() in Responder in: Code 5.7 Exercise 5.43 The modifications needed to the Responder class in the project tech-supportcomplete: Add a new field: private HashMap<String, String> synonymmap;

49 Initialize it in the constructor: synonymmap = new HashMap<String, String>(); Add this to the generateresponse method right after the if-block: else //check if it is a synonym String synonym = synonymmap.get(word); if(synonym!= null) return responsemap.get(synonym); To create an example replace the responsemap.put("crashes","well...); with: synonymmap.put("crashes", "crash"); Exercise These keywords get special attention so they stand out in the documentation. Exercise 5.53 Color.BLUE is used to set the pen color in drawsquare() Color.RED is used in drawwheel() Exercise 5.54 Other colors available in the Color class are BLACK, GREEN, MAGENTA, ORANGE, etc. These are available via both upper-case and lower-case names. Exercise 5.56 Use the clear() method to clear the whole canvas. Exercise 5.57 * Draw a triangle on the screen. public void drawtriangle() Pen pen = new Pen(320, 260, mycanvas);

50 pen.setcolor(color.green); triangle(pen); * Draw a triangle in the pen's color at the pen's location. private void triangle(pen pen) for(int i = 0; i < 3; i++) pen.move(100); pen.turn(120); Exercise 5.58 * Draw a pentagon on the screen. public void drawpentagon() Pen pen = new Pen(320, 260, mycanvas); pen.setcolor(color.magenta); pentagon(pen); * Draw a pentagon in the pen's color at the pen's location. private void pentagon(pen pen) for(int i = 0; i < 5; i++) pen.move(100); pen.turn(360 / 5); Exercise 5.59 * Draw a polygon with the given number of sides. n The number of sides. public void drawpolygon(int n) Pen pen = new Pen(320, 260, mycanvas); pen.setcolor(color.magenta); polygon(pen, n); * Draw a polygon with the given number of side * in the pen's color at the pen's location. sides The number of sides. private void polygon(pen pen, int sides) for(int i = 0; i < sides; i++)

51 pen.move(100); pen.turn(360 / sides); Exercise 5.60 See spiral: * Draw a spiral in the pen's color at the pen's location. private void spiral(pen pen) // The number of arms. int arms = 63; // The current length of the arm being drawn. int armlength = 3; // How much longer to make each arm. int armincrement = 2; // Start in the middle. pen.penup(); Dimension size = mycanvas.getsize(); pen.moveto(size.width / 2, size.height / 2); // Face downwards. pen.turnto(90); pen.pendown(); // Draw arms of increasing length. for(int arm = 0; arm < arms; arm++) pen.move(armlength); pen.turn(90); armlength += armincrement; Exercise 5.62 public void bounce(int numberofballs) int ground = 400; // position of the ground line mycanvas.setvisible(true); // draw the ground mycanvas.drawline(50, ground, 550, ground); // create and show the balls HashSet<BouncingBall> balls = new HashSet<BouncingBall>(); for(int i=0; i < numberofballs; i++) BouncingBall ball = new BouncingBall(50+32*i, 50, 16, Color.blue, ground, mycanvas); balls.add(ball); ball.draw(); // make them bounce boolean finished = false; while(!finished)

52 x axis mycanvas.wait(50); // small delay for(bouncingball ball : balls) ball.move(); // stop once ball has travelled a certain distance on if(ball.getxposition() >= *numberOfBalls) finished = true; for(bouncingball ball : balls) ball.erase(); Exercise 5.63 HashSet is most suitable, because it guaranties that we only have one of each ball in the collection. The HashMap could be used for this as well, but we do not need a map, so it would be a bad choice. Exercise 5.64 // create and show the balls Random random = new Random(); HashSet balls = new HashSet<BouncingBall>(); for(int i=0; i < numberofballs; i++) Dimension size = mycanvas.getsize(); int x = random.nextint((int) size.getwidth()); int y = random.nextint((int) size.getheight()); BouncingBall ball = new BouncingBall(x, y, 16, Color.blue, ground, mycanvas); balls.add(ball); ball.draw(); Exercise Download: balls-inabox.zip Exercise 5.68 public static final double TOLERANCE = 0.001; private static final int PASS_MARK = 40; public static final char HELP_COMMAND = 'h'; Exercise 5.69 Five constants are defined. They are used to index the positions of data in an array. It is a good use of constants.

53 Exercise 5.70 You would only have to modify the values of the constants which are all defined in one place. If these numbers had not been placed in constant fields, but instead used directly, it would have required changes to several different parts of the code. Exercise 5.71 public class NameGenerator public String generatorstarwarsname(string firstname, String lastname, String mothersmaidenname, String cityofbirth) String swfirstname = lastname.substring(0,3) + firstname.substring(0,2); String swlastname = mothersmaidenname.substring(0,2) + cityofbirth.substring(0,3); return swfirstname + " " + swlastname; Exercise 5.72 Strings are immutable and therefore can not be changed. The method that is called does not change the instance 's' but returns a new object with the string in upper case. The correct way to do it is: String uppercases = s.touppercase(); System.out.println(upperCaseS); Exercise 5.73 The variable a and b contains values. When these values are passed as arguments to the method, the values get copied into the variables i1 and i2. So we now have two copies of the values in a and b. In the method, we then swap the values stored in the variables i1 and i2. This has no effect outside the method as i1 and i2 are local variables in the method. After calling the method the variables a and b will still contain the same values as before the method call.

54 Exercise 6.1 a) What does this application do? "World of Zuul" is a very simple, text based adventure game. Users can walk around some scenery. That's all. b) What commands does the game accept? help quit go "somewhere" c) What does each command do? help: Gives information about the commands available quit: Exits the game go "somewhere": Goes through the door in the specified direction. Directions can be one of these: north, east, south, and west. d) How many rooms are in the scenario? There are 5 rooms. e) Draw a map of the existing rooms. Exercise 6.2 The descriptions below are taken from the documentation in the source code of the classes Parser: This parser reads user input and tries to interpret it as an "Adventure" command. Every time it is called it reads a line from the terminal and tries to interpret the line as a two-word command. It returns the command as an object of class Command. The parser has a set of known command words. It checks user input against the known commands, and if the input is not one of the known commands, it returns a command object that is marked as an unknown command. Game:

55 This class is the main class of the "World of Zuul" application. To play this game, create an instance of this class and call the "play" method. This main class creates and initializes all the others: it creates all rooms, creates the parser and starts the game. It also evaluates and executes the commands that the parser returns. Command: This class holds information about a command that was issued by the user. A command currently consists of two strings: a command word and a second word (for example, if the command was "take map", then the two strings obviously are "take" and "map"). The way this is used is: Commands are already checked for being valid command words. If the user entered an invalid command (a word that is not known) then the command word is <null>. If the command had only one word, then the second word is <null>. CommandWords: This class holds an enumeration of all command words known to the game. It is used to recognize commands as they are typed in. Room: A "Room" represents one location in the scenery of the game. It is connected to other rooms via exits. The exits are labeled north, east, south, west. For each direction, the room stores a reference to the neighboring room, or null if there is no exit in that direction. Exercise 6.5 Add the method printlocationinfo() from Code 6.2 to the class Game. Then replace the corresponding lines from the method printwelcome() and goroom() with a call to the method: printlocationinfo() Exercise 6.7 Add this method to the Room class: * Return a string describing the room's exits, for example * "Exits: north west". public String getexitstring() String returnstring = "Exits: "; if(northexit!= null) returnstring += "north "; if(eastexit!= null) returnstring += "east "; if(southexit!= null) returnstring += "south "; if(westexit!= null)

56 returnstring += "west "; return returnstring; Modify printlocationinfo() in the Game class like this: private void printlocationinfo() System.out.println("You are " + currentroom.getdescription()); System.out.print(currentRoom.getExitString()); System.out.println(); Exercise 6.8 See the zuul-better project included on the CD. Exercise 6.9 Taken from the API documentation: Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeall, retainall, and clear operations. It does not support the add or addall operations. Exercise 6.10 First, a string called returnstring is created with the initial text "Exits: ". We will then add the exits to this string and finally return it. The names of the available exits are added by retrieving the set of keys from the HashMap of exits. We then iterate through the set of keys and in each iteration we add the key of the exit to returnstring. Exercise 6.11 See the zuul-better project included on the CD. Exercise 6.12 The objects are: game1:game -->parser:parser --> commands:commandwords -->outside:room -->theatre:room -->lab:room -->office:room -->pub:room

57 Exercise 6.13 The reference from game1:game to the outside:room is changed to the new room that we have moved into. If we use the command go east the reference will be to theatre:room. Exercise 6.14 See page 216 of the fifth edition for the implementation details. Exercise 6.15 private void eat() System.out.println( You have eaten now and you are not hungry any more ): adding: else if(commandword.equals("eat")) eat(); to the command-testing statements. Exercise 6.17 No, you don't need to change Game class. The list of commands which are printed out is generated from the array of validcommands, and will therefore automatically include any new commands that have been added to this array. Exercise 6.18 Modify the printhelp() method in Game so the last lines is: System.out.println(parser.getCommandList()); Add the following method to Parser: public String getcommandlist() return commands.getcommandlist(); And remove the now obsolete showcommands() from Parser (if you implemented this in Exercise 6.16) In CommandWords add this method: public String getcommandlist()

58 String commandlist = ""; for(string command : validcommands) commandlist += command + " "; return commandlist; And remove the now obsolete showcommands() from CommandWords (if you implemented this in Exercise 6.16) Exercise 6.19 Information about the model-view-control (MVC) pattern can be found here: A simple example of a Java program that uses MVC: For more examples of the MVC pattern look at the Java Swing implementation which makes heavy use of the MVC pattern. The MVC pattern is related to the discussion in this chapter because it is a pattern that decouples objects into three types of objects: Model objects which represent the data; View objects which handle the display; and Control objects which handle events that modify the View or Model objects. In this chapter we only discussed the separation of View and Model - adding another level of decoupling makes the design even more flexible. To apply the MVC pattern to the Zuul game, we need to split the application into a model, view and control. We might do something like this: Model: The Game and Room classes represent the model. We might split the Game class into two classes one which represents the model and one which does the rest. The changes we make to the model while playing the game, is to change the game object's reference to the current room. Whenever we change this reference the model should fire an event to all registered listeners (the View). View: We should create a new class which handles the view of the model - that is, printing the text to the screen when an update is received from the model. Controller: As it is now, the control of the game is done from the Game class in the play() and processcommand(command command) methods. An example of Zuul with the MVC pattern applied can be downloaded here: zuul-mvc.zip Exercise 6.20

59 See Exercise (Although the rooms can hold several items) Exercise 6.21 a) How should the information about an item present in a room be produced? The items are in the rooms, and hence the room should produce the information about items present. b) Which class should produce the string describing the item? The Item class should produce the string. c) Which class should print the description of the item? The Game class is responsible for printing, and hence should also print the description of an item. It is, however, not necessary to explicitly print the item description in the game class if the description of the room includes the description of the item in the room. Exercise 6.22 Download: zuul-with-items.zip Exercise 6.23 Add the command "back" to the CommandWords. The rest of the modifications are in the Game class: Add a field: private Room previousroom; In processcommand() add: else if (commandword.equals("back")) goback(command); Introduce a new method enterroom, which stores the previousroom. Update the method goroom() to use this method. * Enters the specified room and prints the description. private void enterroom(room nextroom) previousroom = currentroom; currentroom = nextroom; System.out.println(currentRoom.getLongDescription());

60 Add this method: * Go back to the previous room. private void goback(command command) if(command.hassecondword()) System.out.println("Back where?"); return; if (previousroom == null) System.out.println("You have nowhere to go back to!"); else enterroom(previousroom); Exercise 6.24 When a second word is typed after back, it prints an error message: "Go where?" Another case of negative testing: When the game is just started, there is no previous room. In the above implementation this is handled by printing a message to the user: "You can't go back to nothing!" Exercise 6.25 If back is typed in twice you end up in the same room as where you were when you typed back the first time. Yes this is sensible, but it might be more useful to be able to go back several steps - see the next exercise. Exercise 6.26 Download: zuul-back.zip Exercise 6.27 There are many possible tests for the zuul project. It is important to have both positive and negative tests. Some of the tests could be: - testing that the rooms are properly connected. - testing that all the commands are recognised and works as expected. - testing the back command as explained in the solution to Exercise 6.24 Exercise 6.28 Download: zuul-refactored.zip

61 Exercise All the modifications suggested in Exercises 6.29 through 6.33 is implemented in this project: Download: zuul-with-player.zip Exercise 6.35 Add this in Game.processCommand: else if (commandword == CommandWord.LOOK) look(); And add this method to Game: private void look() System.out.println(currentRoom.longDescription()); And finally, modify the CommandWord to include the new value LOOK: public enum CommandWord // A value for each command word, plus one for unrecognised // commands. GO, QUIT, HELP, LOOK, UNKNOWN; Oh, and don't forget to specify the text associated with the command in the CommandWords constructor: validcommands.put("look", CommandWord.LOOK); Exercise 6.36 Using different command words only requires changes in the CommandWords class. Exercise 6.37 When the command word for help is changed it is NOT changed in the welcome message. Exercise 6.38 public enum Position TOP, MIDDLE, BOTTOM

62 Exercise 6.39 Almost. You also need to add the functionality of it to the Game class. Compared to Exercise 6.35 you have one less class to modify in this exercise. Exercise 6.40 Yes. It is just using the enum itself: CommandWord.HELP. This will return the command string because tostring() has been overridden in CommandWord. Exercise 6.41 Download: zuul-with-timelimit.zip Exercise 6.42 To implement a trapdoor (one way door), simply remove one of the exits. For instance, you could remove the exit from the pub to the outside by removing this line: pub.setexit("east", outside); Exercise 6.43 Download: zuul-with-beamer.zip Exercise 6.44 Download: zuul-with-doors.zip Exercise 6.45 Download: zuul-with-transporter.zip Exercise 6.46 Download: zuul-even-better.zip Exercise 6.49 The method signature is: static int max(int a, int b); Exercise 6.50 The methods in the Math class are static because they implement mathematical function operations their results do not depend on an object's state and they always return the same results given the same arguments. Therefore we do not need an object with state to use them. It is also more convenient that you do not have to create an object before calling the method.

63 Yes, they could have been instance methods, but that would require that you create an instance of the Math class before you could use the methods. The object would have no useful mutable state, only methods. Exercise 6.51 Exercise 6.52 public static long testlooptime() long starttime = System.currentTimeMillis(); for(int i = 1; i <= 100; i++) // Do nothing! long endtime = System.currentTimeMillis(); return endtime - starttime; The main method could look like this: public static void main(string args[]) Game game = new Game(); game.play(); Exercise 6.54 The main method could look like this: public static void main(string args[]) SupportSystem system = new SupportSystem(); system.start(); Exercise 6.55 a) Yes, you can call a static method from an instance method. b) No, you cannot call an instance method from a static method (at least not without first creating an object to call it on). c) Yes, you can call a static method from a static method. Exercise 6.56 Yes, you can use a static field and the constructor(s) of the class to count the number of instantiations. If you have more that one constructor, you would need to increase the count in each of the constructors. This is one way to do it: public class Test

64 private static int instancecount = 0; public Test() instancecount++; public Test(String something) instancecount++; public static int numberofinstances() return instancecount; It is actually possible to avoid the incrementation in each constructor. You can use an initialiser block which is invoked before the constructor call. This is not a structure that is used very often, and you might be best off without telling your students about it. But if someone should ask you about it, here is how it looks: public class Test private static int instancecount = 0; instancecount++; public Test() public Test(String something) public static int numberofinstances() return instancecount

65 Exercises The functionality tested here should all work correctly. Exercise 7.6 It is possible to give a rating of zero. Exercise 7.7 It is possible to down-vote an item to a negative number of votes. Exercise 7.8 The functionality tested here should work correctly, with the exception of the problem exposed in Exercise 7.9. Exercise 7.9 The findmosthelpfulcomment() method fails if there are no comments. There error is a NoSuchElementException. Exercise 7.10 The downvote() method should protect its field from going negative: public void downvote() if(votes > 0) votes--; The ratinginvalid() method should correctly test its boundaries: private boolean ratinginvalid(int rating) return rating < 1 rating > 5; The findmosthelpfulcomment() method should not assume that there is at least one comment: * Return the most helpful comment. The most useful comment is the one with the highest vote * balance. If there are multiple comments with equal highest balance, return any one of * them. * Return null if there are no comments. public Comment findmosthelpfulcomment()

66 Comment best = null; if(comment.size() > 0) Iterator<Comment> it = comments.iterator(); best = it.next(); while(it.hasnext()) Comment current = it.next(); if(current.getvotecount() > best.getvotecount()) best = current; return best; Any change to the code could have knock-on effects on existing code, or introduce additional errors, so it is not safe to assume that previous tests will still be passed. Exercise 7.11 Test Exercise 7.1 Exercise 7.2 Exercise 7.3 Exercise 7.4 Exercise 7.5 Exercise 7.6 Exercise 7.7 Exercise 7.8 Exercise 7.9 Positive or Negative positive positive positive negative positive negative positive and negative (downvoting below zero) positive negative Exercise 7.14 The methods setup() and teardown() are created automatically. Exercise 7.15 Start recording. Create a SalesItem object. Call the addcomment() method to add a comment. Assert that the result should be true. Call the addcomment() method again to add a comment use the same author name as in the previous comment. Assert that the result should be false. Select the End button to finish the recording. Exercise 7.17 An error diagnostic appears in the lower panel of the Test Results window. The first line is: expected:<false> but was:<true>

67 This is followed by a stack-trace which is not particularly informative, but selecting the Show Source button highlights which assertion has failed in the source of the test class. Exercise 7.21 The terminal window shows: Testing the addition operation. The result is: 7 Testing the subtraction operation. The result is: 5 All tests passed. There is no way to know (just from the test output) that the tests passed, because we only get the test result value. So we should not trust it. Exercise 7.22 Calling testplus() returns the value 1. It is not the same result as was returned by testall(). Calling testplus() one more time returns 7. It should always give the same answer. According to the source code it should return 7. Exercise 7.23 No. Exercise 7.24 The testminus() method is similar in structure to the testplus() method. Making a walk through of testminus() obviously makes us want to take a closer look at the minus() method. Furthermore we could make a note to check that negative values are handled correctly. Exercise 7.25 Method called displayvalue leftoperand previousoperator initial state 0 0 ' ' clear() 0 0 ' ' numberpressed(3) 3 0 ' ' plus() 0 3 '+' numberpressed(4) 4 3 '+' equals() 7 0 '+'

68 Exercise 7.26 No. The equals() method does not does not explicitly check the value of the previousoperator when it is '-'. Therefore anything other than a '+' sign will result in a subtraction. Exercise 7.27 Method called displayvalue leftoperand previousoperator initial state 0 0 ' ' clear() 0 0 ' ' numberpressed(3) 3 0 ' ' plus() 0 3 '+' numberpressed(4) 4 3 '+' equals() 7 0 '+' clear() 0 0 '+' It is not in the same state as the previous clear() (the previousoperator differs). This could have a big impact on subsequent calls. This is most likely the source of the inconsistent result we saw in Exercise Exercise 7.28 Two things has come to our attention while doing the walk through: 1. equals() does not explicitly test for the '-' value of previousoperator. 2. clear() does not clear all the fields. The clear() method should be changed to this: public void clear() displayvalue = 0; leftoperand = 0; previousoperator = ' '; The equals() method should be changed to this: public void equals() if(previousoperator == '+') displayvalue = leftoperand + displayvalue; if(previousoperator == '-') displayvalue = leftoperand - displayvalue;

69 else //do nothing leftoperand = 0; Exercise 7.29 Method called displayvalue leftoperand previousoperator initial state 0 0 ' ' clear() 0 0 ' ' numberpressed(9) 9 0 ' ' plus() 0 9 '+' numberpressed(1) 1 9 '+' minus() 0 10 '-' numberpressed(4) 4 10 '-' equals() 6 0 '-' The result should be 6, which is indeed what is in the displayvalue at the end of the walk through. Exercise 7.31 Yes. The output shows the same information as we collected in the table in the previous exercises. Exercise 7.33 Debug statements have to be removed again. Debug statements might be less error prone than the manual walk through. Debug statements might be easier/faster to do (this is probably subjective) Debug statements are easier to use when you need to verify a correction. The activity of doing the manual walk through might give a better understanding of the program. Exercise 7.35 See the project from the cd: calculator-full-solution

70 Exercise 7.37 The bugs in the bricks project are: class Brick: class Pallet: getsurfacearea(): side1 should be side2 in sum() getweight(): 1000 should be getheight(): % should be * getweight(): + baseweight is missing

71 Exercise 8.2 After creating a comment on the MessagePost object it is also displayed when listing the news feed, even though the MessagePost was added to the news feed before setting the comment. This is because the NewsFeed has a reference to the MessagePost object and uses this reference to get the information about the object each time it prints the list. Only one MessagePost object has been created so the NewsFeed must be storing the one that has the comment. Exercise 8.4 When the 'extends Item' is removed from the source of the MessagePost class, then the inheritance arrow in the diagram disappears. Exercise 8.5 Yes, it is possible to call inherited methods through the sub-menu called 'inherited from Post' Exercise 8.6 Add the getusername method to Post: public String getusername() return username; Define printshortsummary in MessagePost: public void printshortsummary() System.out.println("Message post from " + getusername()); Exercise 8.7 First, the Step Into button takes us to the superclass constructor, which on the subsequent Step Into initializes the fields: username, timestamp, likes and comments. Then it returns back to the MessagePost constructor and initializes the last field: message. Exercise 8.8 The EventPost: * This class stores information about a post in a social network news feed. * The main part of the post consists of a (possibly multi-line) * text message. Other data, such as author and time, are also stored. * Michael Kölling and David J. Barnes 0.2

72 public class EventPost extends Post // The type of event. private String eventtype; * Constructor for objects of class EventPost author The author of the post. eventtype The type of event. public EventPost(String author, String eventtype) super(author); this.eventtype = eventtype; * Return the type of event. * The type of event. public String geteventtype() return eventtype; Exercise 8.9. One possible hierarchy: Exercise 8.10 A touch pad and mouse are both input devices for a computer. They are very similar and they could either have a common superclass (InputDevice) or one could be a superclass of the other. Exercise 8.11

73 Argument for a square being a subclass of a rectangle: - a square is just a rectangle where the sides are restricted to be of equal length. Argument for a rectangle being a subclass of a square: - a rectangle is a square that just has an extra attribute: the ratio between the sizes of the width and height Argument for neither: - a rectangle has two attributes determining its shape and a square has just one. If the two attributes of a Rectangle have the same value, is it equivalent to a Square object? Exercise 8.12 a) Which of the following assignments are legal, and why or why not? Person p1 = new Student(); - This is legal because Student is a subclass of Person. Person p2 = new PhDStudent(); - This is legal because PhDStudent is a subclass of Person (because it is a subclass of Student which is subclass of Person) PhDStudent phd1 = new Student(); - This is not legal, because Student is not a subclass of PhDStudent. Teacher t1 = new Person(); - This is not legal because Person is not a subclass of Teacher. Student s1 = new PhDStudent(); - This is legal, because PhDStudent is a subclass of Student. b) Assume that the two illegal lines above are changed to: PhDStudent phd1; Teacher t1; s1 = p1; - This is not legal, because erson is not a subclass of Student. The compiler only knows the static type o p1 which is Person - it does not know the dynamic type which is Student.

74 s1 = p2; - This is not legal, because a Person is not a subclass of Student (same arguments the previous case). p1 = s1; - This is legal because Student is a subclass of Person. t1 = s1; - This is not legal because Student is not a subclass of Teacher. s1 = phd1; - This is legal because PhDStudent is a subclass of Student. phd1 = s1; - This is not legal because Student is not a subclass of PhDStudent. Exercise 8.14 Nothing has to change in the NewsFeed class when we add a new Post subclass. This is because the NewsFeed never worries about the actual subclass, but treats all objects as Posts. Exercise 8.15 From the JDK API documentation, the following class hierarchies can be drawn:

75 Exercise 8.16

76 The solution is in: lab-classes Exercise 8.17 An example of a class hierarchy of some of the components in a computer. Note that the question refers to a DVD drive rather than a CD drive, but the change is trivial. Or maybe this:

77 Exercise 8.18 The legal statements tells us the following: a) m = t This tells us that T is subclass of M b) m = x This tells us that X is a subclass of M c) o = t This tells us that T is a subclass of O. But T was also a subclass of M, and Java does not allow multiple inheritance. Therefore M must be a subclass of O or vice versa. And the illegal statements gives us: d) o = m M is not a subclass of O. Hence from c) we have that O is a subclass of M. e) o = x X is not a subclass of O f) x = o O is not a subclass of X From this information we can be sure that the following relations exist:

78 Exercise 8.19 See the diagram in the solution to exercise 8.15.

79 Exercise 9.1 The project no longer compiles. The display() method tries to access the private fields of the Post class, which are not accessible from subclasses. This can be corrected by creating accessor methods in Post and calling these from the subclasses. If we try to compile after these modifications it still does not work. This time it is in the compilation of the NewsFeed class that fails, because it is trying to invoke the display() method on a variable of type Post. But Post no longer has a method called display() and hence it fails. Exercise 9.2 The display() method in the Post class is never called. If the object is a MessagePost the display() method in the MessagePost class is called. If the object is a PhotoPost the display() method in the PhotoPost class is called. This is because the dynamic types of the items are used. Exercise 9.3 Yes, it behaves as expected by first calling the display() method from the Post class and then calling the display() method in the actual class (dynamic type). One problem is that you can't enforce the call to the super class' display() method. This means that if you want to create new subclasses you must remember to call super.display(). Another problem is that you can't modify the order of which the different things are printed out. This is discussed further in Exercise 9.7. Exercise 9.4 The tostring() method can be found on the class Object. It has no parameters and the return type is String. Exercise 9.6 The display() method in the MessagePost class: public void display() System.out.println(message); super.display(); Exercise 9.7 Give all the fields in the Post class protected accessors.

80 Then modify the display() method in the MessagePost class to look like this: public void display() System.out.println(getUserName()); System.out.println(message); System.out.print(getTimeString()); System.out.println(" " + getlikesstring()); System.out.println(getCommentsString()); Account will have to be taken of the exact format of the strings returned by the accessor methods in Post. Exercise 9.8 Solution in zuul-with-transporter Exercise 9.09 To implement a Monster and a Player class in the Zuul project it would probably make sense to have a common superclass (Character) that contains the common behavior of the two classes. Exercise 9.10 It depends... you could argue for all of the inheritance relations. Which one to choose depends on the current implementation and (if you know) which features you plan to implement in the near future. If an Item is a superclass of a Character, it would allow you to treat all characters as Items. This means that a Character could pick up another Character which might make sense in some scenarios. If Character is a superclass of Item, you can treat all items as Characters. If we define Characters as something that can move around, this would allow for items to move around if that is desired. If the two classes are siblings and have a common superclass (Thing?), you could do a combination of the above solutions. This could allow a character to pick up Things (which means you can pick up both items and characters) and it could also allow for all Things to move around (again, this also applies to Item and Character). If you don't consider Item and Character to have anything in common you could have no inheritance relations between Item and Character at all. Exercise 9.11 Because type-checking is done on the static type of dev (which is Device) the method getname() must be defined in Device.

81 Exercise 9.12 To actually execute a method dynamic method lookup is used. This means that it is the method in the Printer class that will be called, because the dynamic type of dev is Printer. Exercise 9.13 Yes, it will compile. The tostring() is implemented in the class Object from the Java library. The Object class is always a superclass of all other classes. Hence, when you execute it is the tostring() as defined in the class Object that will be called and the return value assigned to the String variable s. Exercise 9.14 Yes, this will compile. The System.out.println() method can take an Object as argument and as argued in Student is a subclass of Object. Exercise 9.15 Yes, it compiles. It prints out all the names of the students in the list. It will run through all the items in the list and call the method System.out.println(st). This method invokes the tostring() method of the object - which, because of dynamic method lookup, will call the tostring() method in the Student class. Exercise 9.16 D must be a subclass of T T x = new D();

82 Exercise 10.1 Yes, the number of foxes changes. However, note that although this has a high probability of happening, it is not guaranteed to and will ultimately depend upon the initial state of the simulation. Exercise 10.2 Yes, in general it changes each time simulateonestep() is invoked. Sometimes the number increase and other times it decreases. It probably simulates the birth and death of foxes. Once again, note that it is highly probably that it will change but there are some states of the simulation when it will not change over the course of a single step. Exercise 10.3 No, the rates vary. Exercise 10.4 The numbers of foxes and rabbits goes up and down. The simulation will stop before the end of the specified number of steps if either animal dies out completely. Exercise 10.5 No, it is not an identical simulation. Yes, it exhibits similar patterns. Exercise 10.6 Yes, sometimes the foxes or rabbits die out completely. If there are many foxes near the rabbit groupings then they may eat all the rabbits. If there are not many rabbits, or the foxes become isolated from them, then the foxes may die of hunger. Exercise 10.8 The reset() method of the Randomizer must be called first, because this affects the creation of the initial populations following a reset in the Simulator. Exercise Distinguishing between genders is only useful if a more accurate simulation of breeding is included in the model. Given the other simplifications in the model, it is unlikely that more accurate breeding patterns would add in a significant way to the lessons learned from the model. Similar effects on numbers are likely to be achievable through other, simpler modifications to existing parameters such as the breeding

83 frequency or litter sizes. Exercise One observation is that the 'environment' is treated as completely uniform any animal can occupy any part of it. A real environment would be far less uniform than this. Feeding has also been treated simplistically, with their being no resource constraints on the rabbits, for instance. In practice, a very large population of rabbits would eat themselves out of their food supply. Exercise Making the breeding probability of the rabbits much lower has the result that the foxes die out quickly because they don't have enough food. Increasing the breeding probability of the rabbits make them spread faster. Exercise Increasing the maximum age for foxes doesn't seem to have a big impact on the number of foxes, suggesting that their survival is largely determined by available food rather than age. Exercise Yes, in some configurations the foxes or the rabbits disappear completely while in others a balance seems to exist. Exercise Yes the size does affect the likelihood of species surviving. With a small field (30x30, say) this is easy to observe. Exercise Running two equal-sized fields, each with half the original area does not seem to affect the viability of the populations over reasonably long runs in this particular model. Exercise As Exercise illustrates, an uneven division resulting in too small an area for one of the partitions will likely lead to extinction of one of the species. Exercise The modified findfood() method: private Location findfood(location location)

84 List<Location> adjacent = field.adjacentlocations(location); Iterator<Location> it = adjacent.iterator(); Location rabbitlocation = null; while(it.hasnext()) Location where = it.next(); Object animal = field.getobjectat(where); if(animal instanceof Rabbit) Rabbit rabbit = (Rabbit) animal; if(rabbit.isalive()) rabbit.setdead(); foodlevel = RABBIT_FOOD_VALUE; rabbitlocation = where; return rabbitlocation; Exercise To implement the suggested changes we need a field with maximum food value: private static final int MAX_FOOD_VALUE = 20; And replace the statement: foodlevel = RABBIT_FOOD_VALUE; with the statements: foodlevel += RABBIT_FOOD_VALUE; if(foodlevel > MAX_FOOD_VALUE) foodlevel = MAX_FOOD_VALUE; Depending on the maximum food value, the foxes seem to survive longer. Exercise The normal fluctuations in numbers often means that the absolute number of individuals for a particular species drops very low from time to time a single-digit figure, for instance. It only requires a run of 'bad luck' i.e., random variation such as the few remaining foxes heading away from the rabbits instead of towards them, or breeding in low numbers for a few cycles to take the population over the cliff-edge of extinction. While this might have a low probability in normal circumstances, the probability will never be zero. It might be worth adding monitoring output to the simulation to show just how low the population levels become, from time to time. Exercise 10.22

85 It appears to be less likely that a balance is established if all animals start at age zero. Exercise It still appears to be difficult to establish a working balanced relationship. The relative size of the initial populations doesn't have a big impact on the outcome of the simulation. Exercise The advantage would be avoiding any possible inconsistency between the content of the Field and the lists of animals. The disadvantage is that it takes time to generate the lists. Exercise There are dead rabbits in the rabbit list that do not appear in the field. This is because the hunt() method in fox is able to eat rabbits from the field, but it does not have access to the rabbit list in order to remove them. Exercise The similar class fields are: private static final int BREEDING_AGE; private static final int MAX_AGE; private static final double BREEDING_PROBABILITY; private static final int MAX_LITTER_SIZE; private static final Random rand = Randomizer.getRandom(); The fox has an additional class field: private static final int RABBIT_FOOD_VALUE; The similar instance fields are: private int age; private boolean alive; private Location location; private Field field; The fox has an additional instance field: private int foodlevel; The constructors are similar, except that the Fox constructor also initializes its food level.

86 The similar methods are: private void incrementage() //except for the values of the static fields private int breed() //except for the values of the static fields private boolean canbreed() //except for the values of the static fields public Location getlocation() public boolean isalive() private void setdead() public void setlocation(location location) The Rabbit class has these methods that the Fox class doesn't have: private void givebirth(list<rabbit> newrabbits) public void run(list<rabbit> newrabbits) And the Fox class has these methods that the Rabbit class doesn't have: private void givebirth(list<fox> newfoxes) public void hunt(list<fox> newfoxes) private void incrementhunger() private Location findfood(location location) Exercise The truly identical methods are: public Location getlocation() public boolean isalive() private void setdead() public void setlocation(location location) Exercise In this case, no. Because it is most likely that we would want to change the value in the future to values different for the Fox and the Rabbit. In general it depends on the actual field. If it can truly be considered a field that will always have the same value for both the Rabbit and the Fox, then it would make sense to treat methods that use that field as identical. Exercise A good way to test it would be to build a set of unit tests that tests the parts of the program that are likely to be affected by the changes. This could be done by creating JUnit test classes for Fox and Rabbit.

87 After each small change to the program we should run the unit tests to see if the program still behaves as expected. Running the program is also a good way to test this program, because it is easy to spot serious errors from the visual output of the program. Exercise See the project foxes-and-rabbits-v2 from the CD. Exercise We have avoided code duplication. The classes Fox and Rabbit are smaller. If we want to add new animals in the future, we already have some functionality available in the Animal class. Exercise We can't treat the Animals as Objects because Object does not define an act() method that we need to use. Exercise Yes, a class must be declared abstract if it has abstract methods. Exercise Yes, a class can be declared as abstract even though it does not contain any abstract methods. Exercise If you want to prohibit instantiation of a class you could declare it abstract. If you know that the class will never be instantiated, declaring it abstract would help other programmers in understanding the code Exercise AbstractCollection, AbstractSet, AbstractMap, AbstractList, AbstractSequentialList. You can see that a class is abstract in the documentation. The first line below the heading says something like: public abstract class AbstractCollection To see which concrete classes extend them, take a look at the class diagram in the

88 solution to Exercise Exercise Yes, you can see that a method is abstract in the API documentation. For instance, in the left column of the Method Summary. We need to know this if we want to extend an abstract class with a concrete class. This tells us which methods that we as a minimum must implement. Exercise Because we use abstract methods in the Animal class which are overridden in the two subclasses Rabbit and Fox. To understand this behavior it is necessary to understand method overriding. Exercise See: foxes-and-rabbits Exercise The graph shows the rise and fall of population numbers of the two species over time. Observe how rises in the fox population tend to follow slightly behind rises in the rabbit population, and then lead on to falls in rabbit numbers, and consequent falls in fox numbers. These linked cycles clearly show how closely related the population numbers are. Exercise We need to put in the definition of the abstract getbreedingage() in the Animal class: protected abstract int getbreedingage(); An implementation of this can be found in the next exercise. Exercise See: foxes-and-rabbits Exercise Yes, breed() can be moved to the Animal class. We then also have to create methods to access the two static fields: BREEDING_PROBABILITY and MAX_LITTER_SIZE. Just as we did in the two previous exercises. Exercise The changes we have made to the Animal, Rabbit and Fox classes did not require us to modify other classes except the Simulator class (disregarding Exercise 10.40

89 where we created the PopulationGenerator). This tells us that the original program had a low degree of coupling and good encapsulation. Exercise See: foxes-and-rabbits Exercise Yes it is possible. See: foxes-and-rabbits Define an abstract method in Animal that returns a new born Animal: * Create a new animal. An animal may be created with age * zero (a new born) or with a random age. * randomage If true, the animal will have a random age. field The field currently occupied. location The location within the field. abstract protected Animal createanimal(boolean randomage, Field field, Location location); This makes it possible to move givebirth() from Fox and Rabbit to Animal as follows: * Check whether or not this animal is to give birth at this step. * New births will be made into free adjacent locations. newborn A list to add newly born animals to. protected void givebirth(list<animal> newborn) // New rabbits are born into adjacent locations. // Get a list of adjacent free locations. Field field = getfield(); List<Location> free = field.getfreeadjacentlocations(getlocation()); int births = breed(); for(int b = 0; b < births && free.size() > 0; b++) Location loc = free.remove(0); newborn.add(createanimal(false, field, loc)); Note that this calls createanimal() rather than creating either a Fox or a Rabbit directly. Fox and Rabbit define concrete versions of createanimal(), such as: protected Animal createanimal(boolean randomage, Field field, Location location) return new Rabbit(randomAge, field, location);

90 Exercise It is necessary to add the import statement of java.util.list to the Actor class - but that is all. Of course, we also need to specify that Animal extends Actor. Furthermore, we should update the text of the Field class (variable names and comments) to reflect the use of Actors instead of Animals. Exercise Classes that extend Actor will now have to implement it instead. Exercise The fields are static and public fields. Interfaces only allow public static final fields. Exercise There are three errors in this program: - The field THRESHOLD is declared private which is not allowed. - It is not allowed to have constructors in interfaces. - It has an implementation of getthreshold() - no implementations allowed in interfaces. Exercise See: foxes-and-rabbits The number of hunters varies. This is because the newly born animals just get placed into the field without checking whether an actor already occupies that field. Only a few changes is necessary in the other classes: - A new method needs to be introduced in the Field class: getrandomlocation() - The populate() method needs to be updated to also create hunters. Exercise ArrayList: LinkedList: ensurecapacity removerange trimtosize addfirst addlast getfirst getlast removefirst removelast

91 The reason that these methods are not defined in the List interface is that the methods are not common to all lists, but are specific for that type of list implementation. Exercise The following interfaces are mentioned: List, Comparator, Comparable Exercise An implementation of a class implementing the Comparable interface: * A class representing some kind of coffee. public class Coffee implements Comparable<Coffee> // The strength of the coffee private int strength; * Create a new coffee with the given strength public Coffee(int strength) this.strength = strength; public int compareto(coffee other) int otherstrength = other.strength; if (strength > otherstrength) return 1; else if (strength < otherstrength) return -1; else return 0; public String tostring() return "" + strength; And a class to test that it is sorted correctly: import java.util.arraylist; import java.util.collection; import java.util.collections; import java.util.iterator; import java.util.list; public class Test

92 public void testcomparable() List<Coffee> coffees = new ArrayList<Coffee>(); coffees.add(new Coffee(10)); coffees.add(new Coffee(2)); coffees.add(new Coffee(10)); coffees.add(new Coffee(20)); coffees.add(new Coffee(5)); Collections.sort(coffees); System.out.println("Coffees in order of strength:"); for(coffee type : coffees) System.out.println(type); Exercise See: foxes-and-rabbits Exercise In the program below, we have created a list of views that all get updated when required. This has been done in a way that allows any number of views to be added. To avoid making a lot of changes to the Simulator class, we have created a new kind of view (named MultiView) that can delegate the method calls to several other views. See: foxes-and-rabbits Exercise The PriorityQueue class might be useful for ordering events. Exercise (This is a duplication of earlier exercises.) a) Yes, an abstract class can have concrete methods. That is just the way it is - if it couldn't have concrete methods it would almost be the same as a Java interface. b) No, a concrete class can not have abstract methods. If it could, it would not be possible to instantiate an object of that class. What implementation should be run when you try to invoke an abstract method that is not implemented? c) Yes, you can have an abstract class without any abstract methods. See exercise Exercise 10.68

93 All the types could be interfaces. Because G and X both are super classes for U (legal: g = u, x = u), and do not have any relationship between them (illegal: g = x, x = g), at least one of G or X must be an interface. Exercise Several possible hierarchies could be created. This is one example: Exercise 10.70

If too much money is inserted the machine takes it all - no refund. If there isn't enough money inserted, it still prints out the ticket.

If too much money is inserted the machine takes it all - no refund. If there isn't enough money inserted, it still prints out the ticket. Exercise 2.2 Zero. Exercise 2.3 If too much money is inserted the machine takes it all - no refund. If there isn't enough money inserted, it still prints out the ticket. Exercise 2.5 It looks almost completely

More information

Package: java.util It generates random numbers An instance is created by using one of the two constructors:

Package: java.util It generates random numbers An instance is created by using one of the two constructors: Exercise 5.2 The documentation contains the following sections: Overall description of the class: its purpose and how to use it A brief summary of the fields A brief summary of the constructors A brief

More information

The class diagram contains only 2 elements: LabClass and Student. The LabClass class is linked to the Student class.

The class diagram contains only 2 elements: LabClass and Student. The LabClass class is linked to the Student class. Instant download and all chapters Solution Manual Objects First with Java A Practical Introduction Using BlueJ 5th Edition David J. Barnes Michael Kolling https://testbankdata.com/download/solution-manual-objects-first-java-practicalintroduction-using-bluej-5th-edition-david-j-barnes-michael-kolling/

More information

Today s Agenda. Quick Review

Today s Agenda. Quick Review Today s Agenda TA Information Homework 1, Due on 6/17 Quick Review Finish Objects and Classes Understanding class definitions 1 Quick Review What is OOP? How is OOP different from procedural programming?

More information

Understanding class definitions

Understanding class definitions Objects First With Java A Practical Introduction Using BlueJ Understanding class definitions Looking inside classes 2.1 Looking inside classes basic elements of class definitions fields constructors methods

More information

CSC 222: Object-Oriented Programming. Fall 2015

CSC 222: Object-Oriented Programming. Fall 2015 CSC 222: Object-Oriented Programming Fall 2015 Understanding class definitions class structure fields, constructors, methods parameters assignment statements conditional statements local variables 1 Looking

More information

Defining Classes. Chap 1 introduced many concepts informally, in this chapter we will be more formal in defining

Defining Classes. Chap 1 introduced many concepts informally, in this chapter we will be more formal in defining Defining Classes Chap 1 introduced many concepts informally, in this chapter we will be more formal in defining Classes, fields, and constructors Methods and parameters, mutators and accessors Assignment

More information

Understanding class definitions. Looking inside classes (based on lecture slides by Barnes and Kölling)

Understanding class definitions. Looking inside classes (based on lecture slides by Barnes and Kölling) Understanding class definitions Looking inside classes (based on lecture slides by Barnes and Kölling) Main Concepts fields constructors methods parameters assignment statements Ticket Machines (an external

More information

public class TicketMachine Inner part omitted. public class ClassName Fields Constructors Methods

public class TicketMachine Inner part omitted. public class ClassName Fields Constructors Methods Main concepts to be covered Understanding class definitions Looking inside classes fields constructors methods parameters assignment statements 5.0 2 Ticket machines an external view Exploring the behavior

More information

CSCI 161 Introduction to Computer Science

CSCI 161 Introduction to Computer Science CSCI 161 Introduction to Computer Science Department of Mathematics and Computer Science Lecture 2b A First Look at Class Design Last Time... We saw: How fields (instance variables) are declared How methods

More information

Scope of this lecture

Scope of this lecture ARRAYS CITS11 2 Scope of this lecture Arrays (fixed size collections) Declaring and constructing arrays Using and returning arrays Aliasing Reading: Chapter 7 of Objects First with Java 6 th Edition Chapter

More information

Grouping objects. Main concepts to be covered

Grouping objects. Main concepts to be covered Grouping objects Collections and iterators 3.0 Main concepts to be covered Collections Loops Iterators Arrays Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling

More information

CITS1001 week 6 Libraries

CITS1001 week 6 Libraries CITS1001 week 6 Libraries Arran Stewart April 12, 2018 1 / 52 Announcements Project 1 available mid-semester test self-assessment 2 / 52 Outline Using library classes to implement some more advanced functionality

More information

Ticket Machine Project(s)

Ticket Machine Project(s) Ticket Machine Project(s) Understanding the basic contents of classes Produced by: Dr. Siobhán Drohan (based on Chapter 2, Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes,

More information

Objects and Classes Lecture 2

Objects and Classes Lecture 2 Objects and Classes Lecture 2 Waterford Institute of Technology January 12, 2016 John Fitzgerald Waterford Institute of Technology, Objects and ClassesLecture 2 1/32 Classes and Objects Example of class

More information

Grouping objects. The requirement to group objects

Grouping objects. The requirement to group objects Grouping objects Introduction to collections 4.0 The requirement to group objects Many applications involve collections of objects: Personal organizers. Library catalogs. Student-record system. The number

More information

Main loop structure. A Technical Support System. The exit condition. Main loop body

Main loop structure. A Technical Support System. The exit condition. Main loop body Main concepts to be covered More sophisticated behavior Using library classes Reading documentation Using library classes to implement some more advanced functionality 5.0 2 The Java class library Thousands

More information

CSC 222: Object-Oriented Programming. Fall 2017

CSC 222: Object-Oriented Programming. Fall 2017 CSC 222: Object-Oriented Programming Fall 2017 Understanding class definitions class structure fields, constructors, methods parameters shorthand assignments local variables final-static fields, static

More information

UNDERSTANDING CLASS DEFINITIONS CITS1001

UNDERSTANDING CLASS DEFINITIONS CITS1001 UNDERSTANDING CLASS DEFINITIONS CITS1001 Main concepts to be covered Fields / Attributes Constructors Methods Parameters Source ppts: Objects First with Java - A Practical Introduction using BlueJ, David

More information

1st Semester Examinations CITS1001 3

1st Semester Examinations CITS1001 3 1st Semester Examinations CITS1001 3 Question 1 (10 marks) Write a Java class Student with three fields: name, mark and maxscore representing a student who has scored mark out of maxscore. The class has

More information

OBJECT INTERACTION. CITS1001 week 3

OBJECT INTERACTION. CITS1001 week 3 OBJECT INTERACTION CITS1001 week 3 2 Fundamental concepts Coupling and Cohesion Internal/external method calls null objects Chaining method calls Class constants Class variables Reading: Chapter 3 of Objects

More information

Grouping Objects (I)

Grouping Objects (I) KTH ROYAL INSTITUTE OF TECHNOLOGY Stockholm Sweden Grouping Objects (I) Managing collections of objects Ric Glassey glassey@kth.se Main concepts to be covered Grouping Objects Using ArrayLists Looping

More information

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177. Programming

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177. Programming s SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177 Programming Time allowed: THREE hours: Answer: ALL questions Items permitted: Items supplied: There is

More information

Scope of this lecture. Repetition For loops While loops

Scope of this lecture. Repetition For loops While loops REPETITION CITS1001 2 Scope of this lecture Repetition For loops While loops Repetition Computers are good at repetition We have already seen the for each loop The for loop is a more general loop form

More information

More sophisticated behaviour

More sophisticated behaviour Objects First With Java A Practical Introduction Using BlueJ More sophisticated behaviour Using library classes to implement some more advanced functionality 2.0 Main concepts to be covered Using library

More information

Unit 1 Lesson 4. Introduction to Control Statements

Unit 1 Lesson 4. Introduction to Control Statements Unit 1 Lesson 4 Introduction to Control Statements Essential Question: How are control loops used to alter the execution flow of a program? Lesson 4: Introduction to Control Statements Objectives: Use

More information

5 More sophisticated behavior

5 More sophisticated behavior Main concepts to be covered 5 More sophisticated behavior Using library classes to implement some more advanced functionality BK Chap. 6 Maps and sets Random number generation Equality vs identity Class

More information

Java Coding 3. Over & over again!

Java Coding 3. Over & over again! Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

More information

MID-SEMESTER TEST 2014

MID-SEMESTER TEST 2014 MID-SEMESTER TEST 2014 CITS1001 Object-Oriented Programming and Software Engineering School of Computer Science and Software Engineering The University of Western Australia First Name Family Name Student

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

CITS1001 week 4 Grouping objects

CITS1001 week 4 Grouping objects CITS1001 week 4 Grouping objects Arran Stewart March 20, 2018 1 / 31 Overview In this lecture, we look at how can group objects together into collections. Main concepts: The ArrayList collection Processing

More information

CMPT 125: Lecture 3 Data and Expressions

CMPT 125: Lecture 3 Data and Expressions CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,

More information

Chapter 4 Introduction to Control Statements

Chapter 4 Introduction to Control Statements Introduction to Control Statements Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives 2 How do you use the increment and decrement operators? What are the standard math methods?

More information

OBJECT INTERACTION CITS1001

OBJECT INTERACTION CITS1001 OBJECT INTERACTION CITS1001 Overview Coupling and Cohesion Internal/external method calls null objects Chaining method calls Class constants Class variables A digital clock Abstraction and modularization

More information

Do not start the test until instructed to do so!

Do not start the test until instructed to do so! CS 1054: Programming in Java Page 1 of 6 Form A READ THIS NOW! Failure to read and follow the instructions below may result in severe penalties Failure to adhere to these directions will not constitute

More information

CS 142 Style Guide Grading and Details

CS 142 Style Guide Grading and Details CS 142 Style Guide Grading and Details In the English language, there are many different ways to convey a message or idea: some ways are acceptable, whereas others are not. Similarly, there are acceptable

More information

Objects and State. COMP1400 Week 9. Wednesday, 19 September 12

Objects and State. COMP1400 Week 9. Wednesday, 19 September 12 Objects and State COMP1400 Week 9 Mutator methods The internal state of an object can change. We do this by changing the values contained in its fields. Methods that change an object's state are called

More information

CS 1316 Exam 1 Summer 2009

CS 1316 Exam 1 Summer 2009 1 / 8 Your Name: I commit to uphold the ideals of honor and integrity by refusing to betray the trust bestowed upon me as a member of the Georgia Tech community. CS 1316 Exam 1 Summer 2009 Section/Problem

More information

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling 2

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling 2 !"# $ Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling 2 % % % & ' &' " Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes,

More information

Structured Programming

Structured Programming CS 170 Java Programming 1 Objects and Variables A Little More History, Variables and Assignment, Objects, Classes, and Methods Structured Programming Ideas about how programs should be organized Functionally

More information

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1 CSC 1051 Algorithms and Data Structures I Midterm Examination February 24, 2014 Name: KEY 1 Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1(c): Java Basics (II) Lecture Contents Java basics (part II) Conditions Loops Methods Conditions & Branching Conditional Statements A

More information

(Refer Slide Time: 00:26)

(Refer Slide Time: 00:26) Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute Technology, Madras Module 07 Lecture 07 Contents Repetitive statements

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

Installing Java. Tradition. DP Computer Science Unit 4.3: Intro to programming 1/17/2018. Software & websites

Installing Java. Tradition. DP Computer Science Unit 4.3: Intro to programming 1/17/2018. Software & websites DP Computer Science Unit 4.3: Intro to programming Installing Java Software & websites JDK (Java development kit) download: http://www.oracle.com/technetwork/java/javase/ Tradition For a full IDE (integrated

More information

(Refer Slide Time: 00:02:02)

(Refer Slide Time: 00:02:02) Computer Graphics Prof. Sukhendu Das Dept. of Computer Science and Engineering Indian Institute of Technology, Madras Lecture - 20 Clipping: Lines and Polygons Hello and welcome everybody to the lecture

More information

Generics. IRS W-9 Form

Generics. IRS W-9 Form Generics IRS W-9 Form Generics Generic class and methods. BNF notation Syntax Non-parametrized class: < class declaration > ::= "class" < identifier > ["extends" < type >] ["implements" < type list >]

More information

Introduction to Classes and Objects

Introduction to Classes and Objects 3 Nothing can have value without being an object of utility. Karl Marx Your public servants serve you right. Adlai E. Stevenson Knowing how to answer one who speaks, To reply to one who sends a message.

More information

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created. + Inheritance + Inheritance Classes that we design in Java can be used to model some concept in our program. For example: Pokemon a = new Pokemon(); Pokemon b = new Pokemon() Sometimes we need to create

More information

Object interactions Lecture 6

Object interactions Lecture 6 Object interactions Lecture 6 Waterford Institute of Technology January 29, 2016 John Fitzgerald Waterford Institute of Technology, Object interactions Lecture 6 1/1 Presentation outline Estimated duration

More information

THE UNIVERSITY OF WESTERN AUSTRALIA. School of Computer Science & Software Engineering CITS1001 OBJECT-ORIENTED PROGRAMMING AND SOFTWARE ENGINEERING

THE UNIVERSITY OF WESTERN AUSTRALIA. School of Computer Science & Software Engineering CITS1001 OBJECT-ORIENTED PROGRAMMING AND SOFTWARE ENGINEERING THE UNIVERSITY OF WESTERN AUSTRALIA School of Computer Science & Software Engineering CITS1001 OBJECT-ORIENTED PROGRAMMING AND SOFTWARE ENGINEERING MID-SEMESTER TEST Semester 1, 2012 CITS1001 This Paper

More information

We will start our journey into Processing with creating static images using commands available in Processing:

We will start our journey into Processing with creating static images using commands available in Processing: Processing Notes Chapter 1: Starting Out We will start our journey into Processing with creating static images using commands available in Processing: rect( ) line ( ) ellipse() triangle() NOTE: to find

More information

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out. Nested Loops To investigate nested loops, we'll look at printing out some different star patterns. Let s consider that we want to print out a square as follows: We know we can print out one line of this

More information

Math Modeling in Java: An S-I Compartment Model

Math Modeling in Java: An S-I Compartment Model 1 Math Modeling in Java: An S-I Compartment Model Basic Concepts What is a compartment model? A compartment model is one in which a population is modeled by treating its members as if they are separated

More information

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 9, Name: KEY

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 9, Name: KEY CSC 1051 Algorithms and Data Structures I Midterm Examination October 9, 2014 Name: KEY Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the

More information

COMP 103 : Test. 2019, Jan 9 ** WITH SOLUTIONS **

COMP 103 : Test. 2019, Jan 9 ** WITH SOLUTIONS ** Family Name:.............................. Other Names:...................................... Signature.................................. COMP 103 : Test 2019, Jan 9 ** WITH SOLUTIONS ** Instructions Time

More information

Practice Midterm 1. Problem Points Score TOTAL 50

Practice Midterm 1. Problem Points Score TOTAL 50 CS 120 Software Design I Spring 2019 Practice Midterm 1 University of Wisconsin - La Crosse February 25 NAME: Do not turn the page until instructed to do so. This booklet contains 10 pages including the

More information

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Loops EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Understand about Loops : Motivation: Repetition of similar actions Two common loops: for and while Primitive

More information

Practice Midterm 1 Answer Key

Practice Midterm 1 Answer Key CS 120 Software Design I Fall 2018 Practice Midterm 1 Answer Key University of Wisconsin - La Crosse Due Date: October 5 NAME: Do not turn the page until instructed to do so. This booklet contains 10 pages

More information

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal The ArrayList class CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Describe the ArrayList class Discuss important methods of this class Describe how it can be used in modeling Much of the information

More information

Turtle Graphics and L-systems Informatics 1 Functional Programming: Tutorial 7

Turtle Graphics and L-systems Informatics 1 Functional Programming: Tutorial 7 Turtle Graphics and L-systems Informatics 1 Functional Programming: Tutorial 7 Heijltjes, Wadler Due: The tutorial of week 9 (20/21 Nov.) Reading assignment: Chapters 15 17 (pp. 280 382) Please attempt

More information

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202

More information

You must bring your ID to the exam.

You must bring your ID to the exam. Com S 227 Spring 2017 Topics and review problems for Exam 2 Monday, April 3, 6:45 pm Locations, by last name: (same locations as Exam 1) A-E Coover 2245 F-M Hoover 2055 N-S Physics 0005 T-Z Hoover 1213

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

CS 455 Midterm 2 Spring 2018 [Bono] Apr. 3, 2018

CS 455 Midterm 2 Spring 2018 [Bono] Apr. 3, 2018 Name: USC NetID (e.g., ttrojan): CS 455 Midterm 2 Spring 2018 [Bono] Apr. 3, 2018 There are 7 problems on the exam, with 59 points total available. There are 10 pages to the exam (5 pages double-sided),

More information

Week 4, Wednesday (Spring 2015). Dr. Yoder. Sec 051. Page 1 of 5

Week 4, Wednesday (Spring 2015). Dr. Yoder. Sec 051. Page 1 of 5 CS2852 Exam 1 Name: No note-sheets, calculators, or other study aids on this exam. Write your initials at the top of each page except this one. Read through the whole exam before you get started. Have

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

CSci 1113, Fall 2015 Lab Exercise 11 (Week 13): Discrete Event Simulation. Warm-up. Stretch

CSci 1113, Fall 2015 Lab Exercise 11 (Week 13): Discrete Event Simulation. Warm-up. Stretch CSci 1113, Fall 2015 Lab Exercise 11 (Week 13): Discrete Event Simulation It's time to put all of your C++ knowledge to use to implement a substantial program. In this lab exercise you will construct a

More information

Model Solutions. COMP 103: Test April, 2013

Model Solutions. COMP 103: Test April, 2013 Family Name:............................. Other Names:............................. ID Number:............................... Signature.................................. Instructions Time allowed: 40 minutes

More information

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes Motivation of Loops Loops EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG We may want to repeat the similar action(s) for a (bounded) number of times. e.g., Print the Hello World message

More information

More Sophisticated Behaviour

More Sophisticated Behaviour More Sophisticated Behaviour Technical Support System V3.0 Produced by: Dr. Siobhán Drohan Mairead Meagher Department of Computing and Mathematics http://www.wit.ie/ Topic List Recap: Technical Support

More information

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 36. Collections Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Introduction Arrays Class Interface Collection and Class Collections ArrayList Class Generics LinkedList Class Collections Algorithms

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lección 03 Control Structures Agenda 1. Block Statements 2. Decision Statements 3. Loops 2 What are Control

More information

Topic 10: The Java Collections Framework (and Iterators)

Topic 10: The Java Collections Framework (and Iterators) Topic 10: The Java Collections Framework (and Iterators) A set of interfaces and classes to help manage collections of data. Why study the Collections Framework? very useful in many different kinds of

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

COMPUTER APPLICATIONS

COMPUTER APPLICATIONS COMPUTER APPLICATIONS (Theory) (Two hours) Answers to this Paper must be written on the paper provided separately. You will not be allowed to write during the first 15 minutes. This time is to be spent

More information

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle Boggle If you are not familiar with the game Boggle, the game is played with 16 dice that have letters on all faces. The dice are randomly deposited into a four-by-four grid so that the players see the

More information

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS These are sample pages from Kari Laitinen s book "A Natural Introduction to Computer Programming with Java". For more information, please visit http://www.naturalprogramming.com/javabook.html CHAPTER 5

More information

COMP-202 Unit 4: Programming with Iterations

COMP-202 Unit 4: Programming with Iterations COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables

More information

Introduction to Classes and Objects

Introduction to Classes and Objects 3 Introduction to Classes and Objects OBJECTIVES In this chapter you will learn: What classes, objects, methods and instance variables are. How to declare a class and use it to create an object. How to

More information

CITS1001 week 4 Grouping objects lecture 2

CITS1001 week 4 Grouping objects lecture 2 CITS1001 week 4 Grouping objects lecture 2 Arran Stewart March 29, 2018 1 / 37 Overview Last lecture, we looked at how we can group objects together into collections We looked at the ArrayList class. This

More information

Assignment3 CS206 Intro to Data Structures Fall Part 1 (50 pts) due: October 13, :59pm Part 2 (150 pts) due: October 20, :59pm

Assignment3 CS206 Intro to Data Structures Fall Part 1 (50 pts) due: October 13, :59pm Part 2 (150 pts) due: October 20, :59pm Part 1 (50 pts) due: October 13, 2013 11:59pm Part 2 (150 pts) due: October 20, 2013 11:59pm Important Notes This assignment is to be done on your own. If you need help, see the instructor or TA. Please

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

COMP-202 Unit 7: More Advanced OOP. CONTENTS: ArrayList HashSet (Optional) HashMap (Optional)

COMP-202 Unit 7: More Advanced OOP. CONTENTS: ArrayList HashSet (Optional) HashMap (Optional) COMP-202 Unit 7: More Advanced OOP CONTENTS: ArrayList HashSet (Optional) HashMap (Optional) Managing a big project Many times, you will need to use an Object type that someone else has created. For example,

More information

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.

More information

Introduction to Java & Fundamental Data Types

Introduction to Java & Fundamental Data Types Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains

More information

Software and Programming 1

Software and Programming 1 Software and Programming 1 Lab 1: Introduction, HelloWorld Program and use of the Debugger 17 January 2019 SP1-Lab1-2018-19.pptx Tobi Brodie (tobi@dcs.bbk.ac.uk) 1 Module Information Lectures: Afternoon

More information

Repetition Structures

Repetition Structures Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Fall 2013 Program/Homework Assignment #2 (100 points) -(Corrected Version)

Fall 2013 Program/Homework Assignment #2 (100 points) -(Corrected Version) CSE 11 START EARLY! Fall 2013 Program/Homework Assignment #2 (100 points) -(Corrected Version) Due: 11 October 2013 at 11pm (2300) Book Exercises Cover Chapters: 3-4 This is a combination of written responses

More information

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution. Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

More information

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements Topic 4 Variables Once a programmer has understood the use of variables, he has understood the essence of programming -Edsger Dijkstra What we will do today Explain and look at examples of primitive data

More information

SEMESTER 1, 2011 EXAMINATIONS. CITS1200 Java Programming FAMILY NAME: GIVEN NAMES:

SEMESTER 1, 2011 EXAMINATIONS. CITS1200 Java Programming FAMILY NAME: GIVEN NAMES: Computer Science & Software Engineering SEMESTER 1, 2011 EXAMINATIONS CITS1200 Java Programming FAMILY NAME: GIVEN NAMES: STUDENT ID: SIGNATURE: This Paper Contains: 26 pages (including title page) Time

More information

Final Exam CS 251, Intermediate Programming December 13, 2017

Final Exam CS 251, Intermediate Programming December 13, 2017 Final Exam CS 251, Intermediate Programming December 13, 2017 Name: NetID: Answer all questions in the space provided. Write clearly and legibly, you will not get credit for illegible or incomprehensible

More information

Mr. Monroe s Guide to Mastering Java Syntax

Mr. Monroe s Guide to Mastering Java Syntax Mr. Monroe s Guide to Mastering Java Syntax Getting Started with Java 1. Download and install the official JDK (Java Development Kit). 2. Download an IDE (Integrated Development Environment), like BlueJ.

More information

More sophisticated behaviour Lecture 09

More sophisticated behaviour Lecture 09 More sophisticated behaviour Lecture 09 Waterford Institute of Technology February 22, 2016 John Fitzgerald Waterford Institute of Technology, More sophisticated behaviour Lecture 09 1/42 Presentation

More information

Topic 4 Expressions and variables

Topic 4 Expressions and variables Topic 4 Expressions and variables "Once a person has understood the way variables are used in programming, he has understood the quintessence of programming." -Professor Edsger W. Dijkstra Based on slides

More information

UMBC CMSC 331 Final Exam

UMBC CMSC 331 Final Exam UMBC CMSC 331 Final Exam Name: UMBC Username: You have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for answers that are needlessly wordy

More information

CSE331 Winter 2014, Midterm Examination February 12, 2014

CSE331 Winter 2014, Midterm Examination February 12, 2014 CSE331 Winter 2014, Midterm Examination February 12, 2014 Please do not turn the page until 10:30. Rules: The exam is closed-book, closed-note, etc. Please stop promptly at 11:20. There are 100 points

More information

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class CS112 Lecture: Defining Classes Last revised 2/3/06 Objectives: 1. To describe the process of defining an instantiable class Materials: 1. BlueJ SavingsAccount example project 2. Handout of code for SavingsAccount

More information