Complete the Location class practice test before reviewing the solution.
Review the Location class practice test with AP CS Tutor Brandon Horn.
Question 1
new Location(4,0);
All GridWorld methods use Location
objects, rather than individual row and column coordinates, to refer to locations. It is occasionally necessary to construct a Location
object given a row and column to use one of the methods.
Question 2
Location.SOUTH
getAdjacentLocation
takes an int
representing a direction as a parameter. Although it is possible to pass in 180
, you should use the Location
class constants to make your code clearer.
Question 3
(B) loc2
will refer to a Location
object representing (5, 0)
.
Although the resulting location is not valid in the grid, the Location
class knows nothing about the grid. This becomes important when you need to use a location obtained from one of the methods in the grid, a common requirement. You must first check if the location is valid using the isValid
method of Grid
.
Question 4
(A) int
Directions in GridWorld are represented as integers. There is no Direction
class in GridWorld.
Question 5
if(dir1 == Location.SOUTH)
System.out.println("pirates");
Directions are represented as type int
in the case study. int
is a primitive types. Values of type int
are compared using ==
, not the equals
method. The Location
class constants are all of type int
.
Question 6
if(loc5.equals(new Location(3,3)))
System.out.println("treasure");
Objects are compared with the equals
method, not ==
. In order to check if a location matches a specific location, you should construct a Location
object. Comparing the row and column values individually duplicates the functionality of an existing method (equals
) and may not receive full credit.
Question 7
Location loc5 = new Location((int) (Math.random() * r), (int) (Math.random() * c));
See Generate random numbers with Math.random().
Question 8
int result = hunterLoc.compareTo(new Location(3,3));
if(result < 0)
System.out.println("Keep going!");
else if(result > 0)
System.out.println("Turn around!");
else
System.out.println("You found it!");
The Location
class implements the Comparable
interface. The compareTo
method orders locations in row major order, which is exactly the order described in this problem.
See compareTo on the AP CS A Exam.