Robotics C++ Physics II AP Physics B Electronics Java Astronomy Other Courses Summer Session  

Mini Review Exercises

MRE 1

MRE 2

MRE 3

MRE 4

MRE 5

MRE 6

MRE 7

 

MRE 1

Part 1: Multiple Choice Prep

 

¢    Which of the following statements is not true?  Circle your selection

 

A. Every List has both an iterator and a ListIterator method.

    True because these are both in the List interface

B. An Iterator for an ArrayList will visit the objects in the list in the same order as the ListIterator 

    for that ArrayList.

    False because the Iterator will always start at the beginning and only move forward.

    The ListIterator can start anywhere and move forward or backward.

C. If a method has a parameter of type Iterator, the method can be called with an argument of

     Type ListIterator.

     True - Both in List interface

D. If a method has a parameter of type ListIterator, the method can be called with an argument

     Of type Iterator.   

     True - Both are in the List interface

E. The hasNext method of an Iterator for a LinkedList of size 0 will always return false.

      Depends. Returns true if has more elements, false otherwise

 

¢    Indicate whether the following statements are true or false by placing a check mark () in the

     appropriate column.

 

Statement

True

False

A list can contain duplicates, but a set cannot

 

A list is an ordered collection, but the items in a set are unordered.

 

A map is an unordered collection of unique keys (that is, there are no duplicates), each of which has an associated object.

 

 

Since a set is an unordered collection, when we add an item to a set it just becomes a member of that set in no particular place within the set, and we cannot ask to remove the kth item, we can only ask to remove a particular item if it is in the set.

 

The different ways to implement a set lead to different running times for the set operations.

 

Deciding whether to store a collection of objects in a list or a set depends on whether ordering is important, whether you want to allow duplicates in the collection, and what operations will be performed most frequently.

 

One small disadvantage of a map (compared to a list or a set) is that maps do not have iterators. However, we can use the keySet method to get the set of keys stored in the collection, and then we can use the set’s iterator to visit each key.  If we want the key’s associated objects, we can use the map’s get method.

 

Using an ArrayList is slightly slower than using an array directly. 

 

An iterator is an object that is attached to the ArrayList and allows you to traverse the array from the first to the last element.

 

 

 

Part 2: Free Response Prep

 

Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.

Notes:

·      Assume that the classes listed in the Quick Reference found in the Appendix have been imported where appropriate.

·      Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied.

·      In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods may not receive full credit.

1. In an instant runoff election there are two or more candidates and there are many voters. Each voter votes by submitting a ballot that is an ordered list of all the  candidates, where the first name listed is the voter’s first choice, the second name is the voter’s second choice, and so on. There are no ties allowed on a voter’s ballot.

The election is decided by the following process.

·         Initially, all candidates are placed on the current candidate list.

·      As long as there are two or more candidates on the current candidate list, the following steps are repeated.

1.   Each ballot is examined for candidates on the current candidate list and a vote is counted for the current candidate that appears earliest in the list of names on the ballot. (On the first pass, this will be the first name on the ballot. In subsequent passes, it might not be the first name on the ballot. See the illustrations below.)

2.   The candidate(s) with the fewest votes is (are) eliminated from the current candidate list.

·      The last remaining candidate is the winner. If there is none, the election is not decisive.

For example, suppose there are four candidates in the election: Chris, Jamie, Pat, and Sandy. Each ballot has these four names listed in order of the voter’s preference, with the first choice appearing first in the list. Assume that seven ballots were submitted as shown in the following table.

Current Candidate List: Chris, Jamie, Pat, Sandy

 

Voter

Ballot

First Choice from Current Candidate List

0

Chris, Jamie, Pat, Sandy

Chris

1

Chris, Pat, Sandy, Jamie

Chris

2

Chris, Sandy, Pat, Jamie

Chris

3

Pat, Jamie, Sandy, Chris

Pat

4

Pat, Sandy, Chris, Jamie

Pat

5

Sandy, Pat, Jamie, Chris

Sandy

6

Jamie, Sandy, Pat, Chris

Jamie

 

In the first pass, Chris has 3 votes, Pat has 2 votes, Sandy has 1 vote, and Jamie has 1 vote. Jamie and Sandy are tied for the fewest votes; so both are eliminated, leaving Chris and Pat on the current candidate list. Voter preferences for these two candidates are shown in the following table.

 

Current Candidate List: Chris, Pat

 

Voter

Ballot

First Choice from Current Candidate List

0

Chris, Jamie, Pat, Sandy

Chris

1

Chris, Pat, Sandy, Jamie

Chris

2

Chris, Sandy, Pat, Jamie

Chris

3

Pat, Jamie, Sandy, Chris

Pat

4

Pat, Sandy, Chris, Jamie

Pat

5

Sandy, Pat, Jamie, Chris

Pat

6

Jamie, Sandy, Pat, Chris

Pat

 

 

In the second pass, Chris has 3 votes and Pat has 4 votes. Chris has fewest votes and is eliminated. Pat is the only remaining candidate and is therefore the winner of the election.

A ballot is modeled with the following partial class declaration.

public class Ballot

{

/** @param candidateList a list of candidate names

* @return the name of the first choice candidate for this Ballot

*from those in candidateList

*/

public String firstChoiceFrom(ArrayList<String> candidateList) { / * implementation not shown * / }

/ / There may be instance variables, constructors, and methods that are not shown.

}

The Ballot method firstChoiceFrom returns the name of the candidate from candidateList that appears first on this ballot. The set of ballots for all voters in an election is modeled with the following partial class declaration.

 

public class VoterBallots

{

private ArrayList<Ballot> ballotList; / / each entry represents one voter’s ballot

/** @param candidate the name of a candidate

* @param candidateList a list of candidate names

*                            Precondition: candidate appears in candidateList

* @return the number of times that candidate is first among

*                                  those in candidateList for elements of ballotList
*/

private int numFirstVotes( String candidate, ArrayList<String> candidateList)

{ / * to be implemented in part (a) * / }

/** @param candidateList a list of candidate names

*Precondition: each String in candidateList appears exactly

*once in each Ballot in ballotList

* @return a list of those candidates tied with the fewest first choice votes */

public ArrayList<String> candidatesWithFewest(ArrayList<String> candidateList)

{ / * to be implemented in part (b) * / }

/ / There may be instance variables, constructors, and methods that are not shown.

 

An instant runoff election is represented by the class Ins tantRunof f that encapsulates the process of selecting a winner by repeatedly applying the VoterBallots method candidatesWithFewest to a list of candidates that is reduced until only the winner remains.

 

This class is not shown here.

 

(a)       Write the VoterBallots method numFirstVotes. Method numFirstVotes should return the number of times candidate appears first, among those elements that are on candidateList, in elements of ballotList.

Complete method numFirstVotes below.

/** @param candidate the name of a candidate

* @param candidateList a list of candidate names

*                                             Precondition: candidate appears in candidateList

* @return the number of times that candidate is first among

*                                                  those in candidateList for elements of ballotList
*/

private int numFirstVotes( String candidate, ArrayList<String> candidateList)

 

Question 1 Answers

(a)   

private int numFirstVotes(String candidate, ArrayList<String> candidateList)

{

    int numVotes = 0;

    for (Ballot voterBallot : ballotList)

   {

         String first = voterBallot.firstChoiceFrom(candidateList);

           if (candidate.equals (first))   numVotes++;

   }

    return numVotes;

}

 


 

(b)    Write the VoterBallots method candidatesWithFewest. MethodcandidatesWithFewest should count the number of times each String in the list candidateList appears first in an element of ballotList, and return an ArrayList of all those Strings that are tied for the smallest count.

In writing method candidatesWithFewest you may use the private helper method numFirstVotes specified in part (a). Assume that numFirstVotes works as specified, regardless of what you wrote in part (a).

 

Complete method candidatesWithFewest below.

 

/** @param candidateList a list of candidate names

*                                    Precondition: each String in candidateList appears exactly

*                                                                 once in each Ballot in ballotList

* @return a list of those candidates tied with the fewest first choice votes */

public ArrayList<String> candidatesWithFewest(ArrayList<String> candidateList)

 

Question 1 Answers

(b)   

public ArrayList<String> candidatesWithFewest(ArrayList<String> candidateList)

{

    int[] votes = new int[candidateList.size()];

    int minVotes = ballotList.size();

    for (int c = 0; c < candidateList.size(); c++)

    {

              String candidate = candidateList.get(c);

              votes[c] = numFirstVotes (candidate, candidateList);

              if (votes[c] < minVotes)
                     minVotes = votes [c];

    }

    ArrayList<String> result = new ArrayList<String>();

    for (int c = 0; c < candidateList.size(); c++)

    {

         if (votes[c] == minVotes)

         result.add(candidateList.get(c));

    }

    return result;

 

(b) Alternate solution

                                        public ArrayList<String> candidatesWithFewest( ArrayList<String> candidateList)

{

    ArrayList<String> result = new ArrayList<String>(); int minVotes = ballotList.size() + 1;

    for (int c = 0; c < candidateList.size();c++)

    {

        String cand idate = candidateList.get(c);

        int thisVotes = numFirstVotes(candidate, candidateList);

         if (thisVotes < minVotes)

          {

             minVotes = thisVotes;

             result = new ArrayList<String>();

           }

              if (thisVotes == minVotes) result.add(candidateList.get(c));

      }

     return result;

 

MRE 2

Directions:

SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.

Notes:

·         Assume that the classes listed in the Quick Reference found in the Appendix have been imported where appropriate.

·         Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only

        when their preconditions are satisfied.

·         In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. ·         Writing significant amounts of code that can be replaced by a call to one of these methods may not receive full

        credit.

 

The following question is somewhat longer than what may appear on the AP Computer Science Exams. In particular, a question of this type appearing on the AP Computer Science A Exam might be limited to two parts. This question could also appear on the AB exam (1 from the A exam usually does).

 

 

Part 1: Multiple Choice Prep

 

 

¢    Indicate whether the following statements are true or false by lacing a check mark () in the appropriate column.

 

Statement

True

False

The TreeMap class implements a map using a balanced tree.

 P

 

The TreeSet class implements a set using a balanced tree.

 P

 

The order of the QuickSort algorithm is logN.

 P

 

A set is a collection of objects with no duplicates.

 P

 

A constructor should initialize the fields of the class.

 P

 

A formal parameter is one of the parameters listed in a method’s header.

 P

 

A HashSet implements a set using a hashtable.

 P

 

A HashTree Implements a hashtable using a balanced tree.

 P

 

An actual parameter is one of the arguments passed when calling a method.

 P

 

 

Part 2: Free Response Prep

 

 

Directions:

 

SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.

 

Notes:

 

·         Assume that the classes listed in the Quick Reference found in the Appendix have been imported where appropriate.

·         Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when

      their preconditions are satisfied.

·         In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question.   

·        Writing significant amounts of code that can be replaced by a call to one of these methods may not receive full credit.

 

The following question is somewhat longer than what may appear on the AP Computer Science Exams. In particular, a question of this type appearing on the AP Computer Science A Exam might be limited to two parts. This question could also appear on the AB exam (1 from the A exam usually does).

 

 

3. Consider the problem of modeling bank accounts. A diagram of the class  hierarchy used to represent bank accounts is shown below.

 

 

 

 

 

The class Account models a bank account with the following data and operations.

 

Data

 

·         the identity number for the account (The identity number is never changed once the account has been constructed.)

·         the balance in the account (The balance can change as a result of some operations.)

 

Operations

 

·    create an account with a given identity number and initial balance

·    return the identity number

·    return the current balance

·    deposit some positive amount into the account, increasing the balance

·       decrease the balance by a specified positive amount; if the amount is greater than the balance, throw an argumentException

·    return the monthly interest due

 

An implementation for this class is shown below.

 

public class Account

{

private int idNum;                       // identity number for this account

private double balance; // current balance for this account

/** Creates an Account with identity number idNumber * and current balance startBal.

* @param idNumber the identity number for the account * @param startBal the starting balance for the account

* Precondition: startBal ≥ 0.0

*/

public Account(int idNumber, double startBal) { / * implementation not shown * / }

/ * * @return the identity number for this account. */

public int idNumber()

{ / * implementation not shown * / }

/ * * @return the current balance for this account. */

public double currentBalance()

{ / * implementation not shown * / }

/ * * Increases the current balance of this account by amount.

* @param amount the amount to be deposited into the account *  

Precondition: amount ≥ 0.0

*/

public void deposit (double amount)

{ / * implementation not shown * / }

/ * * Decreases the current balance of this account by amount.

* @param amount the amount to be removed from the account * 

Precondition: 0 ≤ amount ≤ currentBalance()
*/

public void decreaseBalance (double amount)

{ / * implementation not shown * / }

/ * * @return the monthly interest due for this account. */

public double monthlyInterest()

{     return 0.0;          }

 

(a)  A savings account at a bank “is-a” bank account and is modeled by the class SavingsAccount. A savings account has all the characteristics of a bank account. In addition, a savings account has an interest rate, and the interest due each month is calculated from that interest rate.

 

The operations for a savings account that differ from those specified in the class Account are the following.

 

·         create a new savings account with a given annual interest rate, as well as the parameters required for all accounts

·         withdraw a positive amount that does not exceed the current balance, decreasing the balance by the amount withdrawn

·         calculate the monthly interest by multiplying the current balance by the annual interest rate divided by twelve

 

Write the complete definition of the class SavingsAccount, including the implementation of methods.

 

Possible Answer

public class SavingsAccount extends Account

{

    private double intRate; // annual interest rate for

    // this account

    public SavingsAccount(int idNumber, double balance, double rate)

    {

        super(idNumber, balance);

        intRate = rate;

   }

    public double monthlyInterest()

   {

      return (currentBalance() * (intRate / 12.0));

    }

    public void withdraw(double amount)

   {

        decreaseBalance (amount);

   }

}

MRE 3

Ø The name of the AP computer science case study is the _________________________

    case study.      GridWorld

 

 Ø The three actors included in part 1 are the

 

     Ø  ____________________________  bug

 

     Ø  ____________________________  rock

 

     Ø  ____________________________  flower

   

 Ø List the directions available on the grid.

 

north, south, west, east, northeast, southeast, southwest, northwest

 

Ø The AbstractGrid class include the following line of code:

 

     public ArrayList<E> getNeighbors(Location loc)

 

     What is the meaning of the letter E?

 

  E is  a type variable, which is an unqualified identifier. It simply acts as a placeholder for  

  a type to be defined when the list is used.

 

Ø Five  case study classes that are testable on the AP exam  are on my site and in the notebook for the

    course; they were referred to last week and again today. Name any three of these five

    classes

 

    ¢   ________________________________________________________

    ¢  ________________________________________________________

    ¢  ________________________________________________________

  

  AbstractGrid, BoundedGrid, UnboundedGrid, Grid, Location, Actor, Bug, Flower, Rock,  

  Critter

 

Ø Given a one-dimensional array whose indices go from 0 to n. How do you find the cell that is

     in approximately the middle of the array?   (0 + n)/2

 

Ø Given that myList is a reference to an ArrayList. How do you

 

      ¢  Print the value of the element at index i?

 

            System.out.println (myList.get(i));

 

      ¢  Add a reference to an object to the end of the list?

 

            myList.add("name");

 

      ¢  Add a reference to an object to a given index?

 

            myList.set(indexnumber, "name");

 

Ø Searching

 

      ¢   If an array is not sorted, how do you find an element?

 

            Sequentially - start at the beginning and go to the end

 

      ¢   If an array is sorted, you can use binary search. Explain the operation of this algorithm.

 

          Find the midpoint, it that is the item you are looking for, problem solved.

          If not the item, ask is target larger or smaller than midpoint

          Depending upon answer to above, 1/2 of array can be discarded

          Repeat

 

Ø A binary search tree is shown below. Assume that visit is defined a printing the node.

 

 

    ¢   Write the result of a Preorder traversal:______________________________________ 

 

Mexico City, Los Angeles, Barcelona, Atlanta, Munich, Montreal, Moscow, Seoul, Sydney

 

   ¢   Write the result of a postorder traversal:______________________________________

 

Atlanta, Barcelona, Los Angeles, Moscow, Montreal, Sydney, Seoul, Munich, Mexico City

 

Ø What ensures that a grid has at least one valid location?

 

The constructor for the BoundedGrid will throw an IllegalArgumentException if the number of rows <= 0 or the number of cols <= 0.

 

Extra Credit

P.A.M. Dirac

¢   What do the initials stand for

Paul Adrien Maurice

¢   Where was he born - country

England

¢   Major contributions (name 1)

Dirac, was a British theoretical physicist; he made fundamental contributions to the early development of both quantum mechanics and quantum electrodynamics. He held the Lucasian Chair of Mathematics at the University of Cambridge. Among other discoveries, he formulated the Dirac equation, which describes the behavior of fermions and which led to the prediction of the existence of antimatter. Dirac shared the Nobel Prize in physics for 1933 with Erwin Schrödinger, "for the discovery of new productive forms of atomic theory.

¢   What is the Dirac delta function - plain English description 

It is a function representing an infinitely sharp peak bounding unit area: a function that has the value zero everywhere except at x = 0 where its value is infinitely large in such a way that its total integral is 1. In the context of signal processing it is often referred to as the unit impulse function. Note that this is not strictly a function.  

MRE 4

Part 1: Maps

 

¢  Write field declarations

 

Note that an instance variable is also sometimes referred to as a field.

Assume there exists a Student class with the following methods:

 

String getName();                        //returns the student’s name

double getGPA();                        //returns the student’s GPA

void addGrade(int grade);             //adds the given grade to this student’s list of grades (updating the GPA)

 

Also assume that you have a University class with two Map fields, both of which have ID numbers (Strings) as their keys and Student as the associated values. 

The first map is for Honors students, and the second map is for all other students. Honor students are those students whose GPAs are 3.5 or higher.

 

Write the two field declarations of the University class (honorsStudents and otherStudents) below

 

Ø  field declaration for honorsStudents

 

    Private Map<String, Student> honorsStudents;

 

Ø  field declaration for otherStudents

 

    private Map<String, Student> otherStudents;

 

¢  Multiple-Choice

 

Assume that variable M is a Map. Consider the following code segment:

 

M.put(“1”, “apple”);

M.put(“2”, “banana”);

M.put(“3”, “orange”);

M.put(“1”, “orange”);

M.put(“2”, “plum”);

M.put(“4”, “banana”);

 

If M is empty before the code segment executes, which of the following best shows what it contains after the code segment executes? (circle correct answer).

 

A. (1, apple) (1, orange) (2, banana) (2, plum) (3, orange) (4, banana)

B. (1, orange) (2, plum) (3, orange) (4, banana)                ANSWER

C. (1, orange) (2, plum) (4, banana)

D. (1, apple, orange) (2, banana, plum) (3, orange) (4, banana)

E. (1, 3, apple, orange) (2, 4, banana, plum)

 

 

Part 2: Order of Algorithms

 

¢  Fill in the blank.

 

When designing data structures and algorithms, it is important to consider their _______________ and time requirements.  space

 

¢  In the space provided below list the order of the algorithm associated with each stated activity as O(1), O(N), O(logN), O(NlogN) or O(N2).

 

Activity

Order of Algorithm

Adding a new node to a linked list with N nodes currently

O(1)

Removing the last node from an array with N elements

O(1)

Displaying elements In a 1-D array with N elements

O(N)

Binary search of a sorted array with N elements

O(logN)

Binary search of a binary search tree with N nodes

O(logN)

Merge Sort of a 1-D array with N nodes

O(NlogN)

Bubble Sort of a 1-D array with N nodes

O(N2)

Quick Sort of a 1-D array with N nodes

O(NlogN)

Amount of space needed to store a 2-D square array with N rows goes as

O(N2) or N2

 

¢  The next question refers to the following.

 

A teacher needs a data structure to store information about student absences each day of the 80-day semester. There are N students in the class. Two different

 designs are being considered.

 

Design 1:

A one-dimensional array with 80 elements. Each element of the array is an ArrayList of N strings. Each string is either “absent” or “present”.

 

Design 2:

A two-dimensional array with 80 rows and N columns. Each element of the array contains a boolean value (true or false).

 

Assume that more space is required to store a string than to store a boolean.

 

Ø  Which of the following statements about the space requirements of the two designs is true? Circle the correct answer.

 

     A.  Design 1 will require more space than Design 2.       ANSWER

     B.  Design 2 will require more space than Design 1.

     C.  Designs 1 and 2 will require the same amount of space.

     D. Which design will require more space depends on how many students are actually absent during the semester.

     E. Which design will require more space depends on the value of N.

MRE 5

Part 1: Linked Lists

 

For the following 3 questions, assume that the following method has been added to the standard ListNode class (line numbers are included for reference).

 

1  public void printList()

    {

2        System.out.print(value);

3        if (next  != null)  next.printList();

    }

 

Assume that variable L is a ListNode and has been initialized as described below:

 

L, a reference variable, holds a reference to the first node of a 5 node linked list. The nodes contain the following values in the order listed (L holds a reference to the node containing H): H E L L O.

 

¢  What is the result of the call L.printList()? Circle the correct answer.

 

A. HELLO           ANSWER

B. OLLEH

C. HLO

D. OLH

E. HHHHH

 

¢  Which of the following best characterizes the running time of method printList when it is called for a list containing N nodes? Circle the correct answer.

 

A. O(1)

B O(logN)

C. O(N)            ANSWER

D. O(NlogN)    

E. O(N2)

 

¢  Assume that lines 2 and 3 of method printList are reversed. Now what is output as the result of the call L.printList()?   

 

A. HELLO          

B. OLLEH        ANSWER

C. HLO

D. OLH

E. HHHHH

 

¢  Assume that variable L is a List<String> containing the following 3 strings:

 

   “Mon”    “Tues”    “Wed”

 

Consider the following code segment

 

Iterator<String> it = L.iterator();

for (int k = 0; k<4; k++)

{

    System.out.printLn(it.next());

}

 

What happens when this code segment executes? Circle the correct answer. 

 

A. An exception is thrown because of a call to it.next when there are no more items to be visited.    Answer

B. No exception is thrown; the output is Mon Tues Wed.

C. No exception is thrown; the output is Mon Tues Wed Wed.

D. No exception is thrown; the output is Mon Tues Wed Mon.

E. No exception is thrown; the output is Mon Tues Wed null.

 

Part 2: Sets

 

¢  Indicate whether the following statements are true or false by placing a check mark (P) in the

    appropriate column.

 

Statement

True

False

A set is a collection that has duplicate elements

 

P

The set interface allows you to insert an element and to remove an element

P

 

The set interface allows you to iterate over the elements using Iterator

P

 

The elements of a set do not have to be in order

P

 

 

¢  Assume that variable S is a Set. Consider the following code segment (using non-gerbil formatting):

 

for (int k = 0; k<10; k++)

{

    S.add(new Integer(k));

}

for (int k = 1; k<10; k+=2)

{

    S.add(new Integer (k));

}

 

If S.size() returns 0 before the code segment executes, what does it return after the code segment executes?

 

A. 0

B. 5

C. 10        ANSWER

D. 15

E. 20

MRE 6

¢  Does the bug always move to a new location? Explain.

 

No. A bug will only move to the location in front of it if the cell exists and is empty or if there is a flower in the cell.

 

¢  In which direction does the bug move?

 

A bug attempts to move forward.

 

¢  What does the bug do if it does not move?

 

When a bug cannot move, it turns 45 degrees to the right.

 

¢  What does a bug leave behind when it moves?

 

A bug leaves a flower in its old cell when it moves to a new cell. The flower is the same color as the bug.

 

¢  What happens when a bug has a rock in the location immediately in front of it?

 

The bug turns 45 degrees to the right.

 

¢  Does a flower move?

 

No.

 

¢  What behavior does a flower have?

 

A flower “wilts” over time. The color of a flower gets darker until it turns a dark gray.

 

¢  Does a rock move or have any other behavior?

 

No. A rock stays in its location and does not appear to have any other behaviors when the step or run button is used.

 

¢  Can more than one actor (bug, flower, rock) be in the same location in the grid at the same

    time?

 

No. A location in the grid can contain only one actor at a time.

 

¢  What is the role of the instance variable sideLength?

 

The sideLength instance variable defines the number of steps a BoxBug moves on each side of its box.

 

 

¢  What is the role of the instance variable steps?

 

The steps instance variable keeps track of how many steps a BoxBug has moved on the current side of its box.

 

¢  After a BoxBug is constructed, will the size of its square pattern always be the same?

   Why or why not?

 

Yes. When a BoxBug is constructed, the side length is determined and cannot be changed by client code.

 

¢  Can the path a BoxBug travels ever change? Why or why not?

 

Yes. If another Actor, like a Rock or Bug, is in front of a BoxBug when it tries to move, the BoxBug will turn and start a new box path.

 

¢  Study the code for the BoxBugRunner class. Summarize the steps you would use to add    

    another BoxBug actor to the grid.

 

1. Create a BoxBug object with the desired side length

BoxBug anotherOne = new BoxBug(2);

2. Add the new BoxBug to the word at a random or specific location

world.add(anotherOne);

or

world.add(new Location(1,1), anotherOne);

 

¢  Assume the following statements to answer the following 3 questions.

 

    Location loc1 = new Location(4,3);

    Location loc2 = new Location(3,4);

 

     Ø  How would you access the row value for loc1?

 

       loc1.getRow()

 

     Ø  What is the value of b after the following statement is executed?

        boolean b = loc1.equals(loc2);

 

        false

 

     Ø  What is the value of loc3 after the following statement is exectued?

        Location loc3 = loc2.getAdjacentLocation(Location.SOUTH);

 

        (4,4)

 

 

¢  Which statement(s) in the canMove method ensures that a bug does not try to move out of its

    grid?

 

if(!gr.isValid(next))

return false;

This statement makes sure that the next location is a valid location in the grid.

 

 

¢  Which statement(s) in the canMove method determines that a bug will not walk into a rock?

 

Actor neighbor = gr.get(next);

return (neighbor == null) || (neighbor instanceof Flower);

 

These two statements work together to make sure that a bug will only travel to the next location if it is unoccupied or occupied by a flower.

 

 

¢  What happens in the move method when the location immediately in front of the bug is out of

    the grid?

 

The bug will remove itself from the grid.

 

¢  Is the variable loc needed in the move method, or could it be avoided by calling getLocation()

    muliple times?

 

Yes, the variable loc is needed. The variable loc stores the bug’s location before it moves. It is used to insert a flower in the bug’s old location after the bug has moved to its new location.

 

¢  Which statement(s) in the move method places the flower into the grid at the bug’s previous

    location?

 

Flower flower = new Flower(getColor());

flower.putSelfInGrid(gr, loc); //loc is the old location of the bug

 

¢  What are the five basic actions common to all critters when they act?

 

getActors, processActors, getMoveLocations, selectMoveLocation, makeMove

 

¢  Why is there no Critter constructor?

 

Critter extends Actor. The Actor class has a default constructor. If you do not create a constructor in a class, Java will write a default constructor for you. The Critter default constructor that Java provides will call super(), which calls the Actor default constructor. The Actor default constructor will make a blue critter that faces north.

 

¢  Which class contains the getLocation method?

 

The Actor class contains the getLocation method. All Actor subclasses inherit this method.