Practice MCQs - Unit 7 Part A

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

In the code segment below, assume that the ArrayList object numbers has been properly declared and initialized to contain [0, 2, 4, 5]. for (int k = numbers.size() - 1; k >= 0; k--) { if (numbers.get(k) > k) { System.out.print(k + " "); } } What, if anything, is printed as a result of executing the code segment?

3 2 1

In the following code segment, assume that the ArrayList data has been initialized to contain the Integer values [4, 3, 4, 5, 3, 4]. int j = 0; while (j < data.size() - 1) { if (data.get(j) > data.get(j + 1)) { System.out.print(data.get(j + 1) + " "); } j++; } What, if anything, is printed as a result of executing the code segment?

3 3

In the following code segment, assume that the ArrayList wordList has been initialized to contain the String values ["apple", "banana", "coconut", "lemon", "orange", "pear"]. int count = 0; for (String word : wordList) { if (word.indexOf("a") >= 0) { count++; } } System.out.println(count); What is printed as a result of executing the code segment?

4

Consider the following class definition. public class Value { private int num; public int getNum() { return num; } // There may be instance variables, constructors, and methods not shown. } The following method appears in a class other than Value. It is intended to sum all the num instance variables of the Value objects in its ArrayList parameter. /** Precondition: valueList is not null */ public static int getTotal(ArrayList<Value> valueList) { int total = 0; /* missing code */ return total; } Which of the following code segments can replace /* missing code */ so the getTotal method works as intended? for (int x = 0; x < valueList.size(); x++){ total += valueList.get(x).getNum();} for (Value v : valueList){ total += v.getNum();} for (Value v : valueList){ total += getNum(v);}

I and II

Consider the following statement, which is intended to create an ArrayList named values that can be used to store Integer elements. /* missing code */ = new ArrayList<>(); Which of the following can be used to replace /* missing code */ so that the statement compiles without error? ArrayList values ArrayList<int> values ArrayList<Integer> values

I and III only

Consider the following declaration of the class NumSequence, which has a constructor that is intended to initialize the instance variable seq to an ArrayList of numberOfValues random floating-point values in the range [0.0, 1.0). public class NumSequence { private ArrayList<Double> seq; // precondition: numberOfValues > 0 // postcondition: seq has been initialized to an ArrayList of // length numberOfValues; each element of seq // contains a random Double in the range [0.0, 1.0) public NumSequence(int numberOfValues) { /* missing code */ } } Which of the following code segments could be used to replace /* missing code */ so that the constructor will work as intended? I. ArrayList<Double> seq = new ArrayList<Double>(); for (int k = 0; k < numberOfValues; k++) seq.add(new Double(Math.random())); II. seq = new ArrayList<Double>(); for (int k = 0; k < numberOfValues; k++) seq.add(new Double(Math.random())); III. ArrayList<Double> temp = new ArrayList<Double>(); for (int k = 0; k < numberOfValues; k++) temp.add(new Double(Math.random())); seq = temp;

II and III

Consider the following method. /** Removes all occurrences of nameToRemove from nameList. * @param nameList a list of names * @param nameToRemove a name to be removed from nameList */ public void removeName(List<String> nameList, String nameToRemove) { /* missing implementation */ } Which of the following can be used to replace /* missing implementation */ so that removeName will work as intended? for (String name : nameList) { if (name.equals(nameToRemove)) name.remove(); } for (int k = 0; k < nameList.size(); k++) { if (nameList.get(k).equals(nameToRemove)) nameList.remove(k); } for (int k = nameList.size() - 1; k >= 0; k--) { if (nameList.get(k).equals(nameToRemove)) nameList.remove(k); }

III only

The following method is intended to remove all elements of an ArrayList of integers that are divisible by key and add the removed elements to a new ArrayList, which the method returns. public static ArrayList<Integer> match(ArrayList<Integer> numList, int key) { ArrayList<Integer> returnList = new ArrayList<Integer>(); int i = 0; while (i < numList.size()) { int num = numList.get(i); if (num % key == 0) { numList.remove(i); returnList.add(num); } i++; } return returnList; } As an example, if the method is called with an ArrayList containing the values [5, 2, 10, 20, 16] and the parameter key has the value 5, then numList should contain [2, 16] at the end of the method and an ArrayList containing [5, 10, 20] should be returned. Which of the following best explains why the method does not always work as intended?

The method skips some elements of numList during the traversal.

Consider the following code segment. ArrayList<String> numbers = new ArrayList<String>(); numbers.add("one"); numbers.add("two"); numbers.add(0, "three"); numbers.set(2, "four"); numbers.add("five"); numbers.remove(1); Which of the following represents the contents of numbers after the code segment has been executed?

["three", "four", "five"]

Consider the following method. Assume that a List<Integer> values initially contains the following Integer values. What will values contain as a result of executing mystery(values) ?

[0, 4, 2, 5, 3]

Consider the following code segment. ArrayList<Integer> nums = new ArrayList<Integer>(); nums.add(new Integer(37)); nums.add(new Integer(3)); nums.add(new Integer(0)); nums.add(1, new Integer(2)); nums.set(0, new Integer(1)); nums.remove(2); System.out.println(nums); What is printed as a result of executing the code segment?

[1, 2, 0]

Consider the following code segment. ArrayList<Integer> numList = new ArrayList<Integer>(); numList.add(3); numList.add(2); numList.add(1); numList.add(1, 0); numList.set(0, 2); System.out.print(numList); What is printed by the code segment?

[2, 0, 2, 1]

Consider the following code segment. ArrayList<Integer> oldList = new ArrayList(); oldList.add(100); oldList.add(200); oldList.add(300); oldList.add(400); ArrayList<Integer> newList = new ArrayList(); newList.add(oldList.remove(1)); newList.add(oldList.get(2)); System.out.println(newList); What, if anything, is printed as a result of executing the code segment?

[200, 400]

Consider the following method. Which of the following is printed as a result of executing the following statement?System.out.println(mystery ( 6 ) ) ;

[4, 7, 12, 19, 28, 39]

Consider the following data field and method. private ArrayList list; public void mystery(int n) { for (int k = 0; k < n; k++) { Object obj = list.remove(0); list.add(obj); } } Assume that list has been initialized with the following Integer objects. [12, 9, 7, 8, 4, 3, 6, 11, 1] Which of the following represents the list as a result of a call to mystery(3)?

[8, 4, 3, 6, 11, 1, 12, 9, 7]

Consider the following code segment. ArrayList<Double> conditionRating = new ArrayList<Double>(); conditionRating.add(9.84); conditionRating.add(8.93); conditionRating.add(7.65); conditionRating.add(6.24); conditionRating.remove(2); conditionRating.set(2, 7.63); System.out.println(conditionRating); What is printed when this code segment is executed?

[9.84, 8.93, 7.63]

Consider the following code segment. What is printed as a result of executing the code segment?

[dog, fish, cat]

Consider the following method that is intended to modify its parameter nameList by replacing all occurrences of name with newValue. public void replace(ArrayList<String> nameList, String name, String newValue) { for (int j = 0; j < nameList.size(); j++) { if ( /* expression */ ) { nameList.set(j, newValue); } } } Which of the following can be used to replace /* expression */ so that replace will work as intended?

nameList.get(j).equals(name)

Consider the following code segment. What is printed as a result of executing the code segment?

Alex Bob Carl Alex Alex Alex

Which of the following is a reason to use an ArrayList instead of an array?

An ArrayList resizes itself as necessary when items are added, but an array does not.

Consider the following statement, which is intended to create an ArrayList named years that can be used to store elements both of type Integer and of type String. /* missing code */ = new ArrayList(); Which of the following can be used to replace /* missing code */ so that the statement compiles without error?

ArrayList years

Consider the following method, which is intended to return a list containing the elements of the parameter myList with all even elements removed. public static ArrayList<Integer> removeEvens(ArrayList<Integer> myList) { for (int i = 0; i < myList.size(); i++) { if (myList.get(i) % 2 == 0) { myList.remove(i); } } return myList; } Which of the following best explains why the code segment does not work as intended?

The code segment skips some elements of myList because the indexes of all subsequent elements change by one when a list element is removed.

Consider the following code segment. ArrayList<String> animals = new ArrayList<>(); animals.add("fox"); animals.add(0, "squirrel"); animals.add("deer"); animals.set(2, "groundhog"); animals.add(1, "mouse"); System.out.println(animals.get(2) + " and " + animals.get(3)); What is printed as a result of executing the code segment?

fox and groundhog

The following questions refer to the code in the GridWorld case study. A copy of the code is provided below. Consider the design of a Grasshopper class that extends Bug. When asked to move, a Grasshopper moves to a randomly chosen empty adjacent location that is within the grid. If there is no empty adjacent location that is within the grid, the Grasshopper does not move, but turns 45 degrees to the right without changing its location. Appendix B — Testable API info.gridworld.grid.Location class (implements Comparable) public Location(int r, int c) constructs a location with given row and column coordinates public int getRow() returns the row of this location public int getCol() returns the column of this location public Location getAdjacentLocation(int direction) returns the adjacent location in the direction that is closest to direction public int getDirectionToward(Location target) returns the closest compass direction from this location toward target public boolean equals(Object other) returns true if other is a Location with the same row and column as this location; false otherwise public int hashCode() returns a hash code for this location public int compareTo(Object other) returns a negative integer if this location is less than other, zero if the two locations are equal, or a positive integer if this location is greater than other. Locations are ordered in row-major order. Precondition: other is a Location object. public String toString() returns a string with the row and column of this location, in the format (row, col) Compass directions: public static final int NORTH = 0; public static final int EAST = 90; public static final int SOUTH = 180; public static final int WEST = 270; public static final int NORTHEAST = 45; public static final int SOUTHEAST = 135; public static final int SOUTHWEST = 225; public static final int NORTHWEST = 315; Turn angles: public static final int LEFT = -90; public static final int RIGHT = 90; public static final int HALF_LEFT = -45; public static final int HALF_RIGHT = 45; public static final int FULL_CIRCLE = 360; public static final int HALF_CIRCLE = 180; public static final int AHEAD = 0; info.gridworld.grid.Grid<E> interface int getNumRows() returns the number of rows, or -1 if this grid is unbounded int getNumCols() returns the number of columns, or -1 if this grid is unbounded boolean isValid(Location loc) returns true if loc is valid in this grid, false otherwise Precondition: loc is not null E put(Location loc, E obj) puts obj at location loc in this grid and returns the object previously at that location (or null if the location was previously unoccupied). Precondition: (1) loc is valid in this grid (2) obj is not null E remove(Location loc) removes the object at location loc from this grid and returns the object that was removed (or null if the location is unoccupied) Precondition: loc is valid in this grid E get(Location loc) returns the object at location loc (or null if the location is unoccupied) Precondition: loc is valid in this grid ArrayList<Location> getOccupiedLocations() returns an array list of all occupied locations in this grid ArrayList<Location> getValidAdjacentLocations(Location loc) returns an array list of the valid locations adjacent to loc in this grid Precondition: loc is valid in this grid ArrayList<Location> getEmptyAdjacentLocations(Location loc) returns an array list of the valid empty locations adjacent to loc in this grid Precondition: loc is valid in this grid ArrayList<Location> getOccupiedAdjacentLocations(Location loc) returns an array list of the valid occupied locations adjacent to loc in this grid Precondition: loc is valid in this grid ArrayList<E> getNeighbors(Location loc) returns an array list of the objects in the occupied locations adjacent to loc in this grid Precondition: loc is valid in this grid info.gridworld.actor.Actor class public Actor() constructs a blue actor that is facing north public Color getColor() returns the color of this actor public void setColor(Color newColor) sets the color of this actor to newColor public int getDirection() returns the direction of this actor, an angle between 0 and 359 degrees public void setDirection(int newDirection) sets the direction of this actor to the angle between 0 and 359 degrees that is equivalent to newDirection public Grid<Actor> getGrid() returns the grid of this actor, or null if this actor is not contained in a grid public Location getLocation() returns the location of this actor, or null if this actor is not contained in a grid public void putSelfInGrid(Grid<Actor> gr, Location loc) puts this actor into location loc of grid gr. If there is another actor at loc, it is removed. Precondition: (1) This actor is not contained in a grid (2) loc is valid in gr public void removeSelfFromGrid() removes this actor from its grid. Precondition: this actor is contained in a grid public void moveTo(Location newLocation) moves this actor to newLocation. If there is another actor at newLocation, it is removed. Precondition: (1) This actor is contained in a grid (2) newLocation is valid in the grid of this actor public void act() reverses the direction of this actor. Override this method in subclasses of Actor to define types of actors with different behavior public String toString() returns a string with the location, direction, and color of this actor info.gridworld.actor.Rock class (extends Actor) public Rock() constructs a black rock public Rock(Color rockColor) constructs a rock with color rockColor public void act() overrides the act method in the Actor class to do nothing info.gridworld.actor.Flower class (extends Actor) public Flower() constructs a pink flower public Flower(Color initialColor) constructs a flower with color initialColor public void act() causes the color of this flower to darken Consider the following method that is intended to return an ArrayList of all the locations in grd that contain actors facing in direction dir. public ArrayList<Location> findLocsFacingDir(int dir, Grid<Actor> grd) { ArrayList<Location> desiredLocs = new ArrayList<Location>(); for (Location loc : grd.getOccupiedLocations()) { if ( /* expression */ == dir ) desiredLocs.add(loc); } return desiredLocs; } Which of the following can be used to replace /* expression */ so that findLocsFacingDir will work as intended?

grd.get(loc).getDirection()

Assume that myList is an ArrayList that has been correctly constructed and populated with objects. Which of the following expressions produces a valid random index for myList?

(int) ( Math.random () * myList.size () )

Consider the following instance variable and method. Method wordsWithCommas is intended to return a string containing all the words in listOfWords separated by commas and enclosed in braces.For example, if listOfWords contains ["one", "two", "three"], the string returned by the call wordsWithCommas () should be "{one, two, three}". Which of the following can be used to replace /* expression */ and /* condition */ so thatwordsWithCommas will work as intended?

/ * expression * / / / * condition * / listOfWords.size() / k != sizeOfList - 1

Consider the following statement, which is intended to create an ArrayList named theater_club to store elements of type Student. Assume that the Student class has been properly defined and includes a no-parameter constructor. ArrayList<Student> theater_club = new /* missing code */; Which choice can replace /* missing code */ so that the statement compiles without error?

ArrayList<Student>()

Consider the following code segment. ArrayList<String> items = new ArrayList<String>(); items.add("A"); items.add("B"); items.add("C"); items.add(0, "D"); items.remove(3); items.add(0, "E"); System.out.println(items); What is printed as a result of executing the code segment?

[E, D, A, B]

Consider the following code segment. ArrayList<String> colors = new ArrayList<String>(); colors.add("Red"); colors.add("Orange"); colors.set(1, "Yellow"); colors.add(1, "Green"); colors.set(colors.size() - 1, "Blue"); colors.remove(0); System.out.println(colors); What is printed as a result of executing the code segment?

[Green, Blue]


Kaugnay na mga set ng pag-aaral

Chapter 51: Assessment and Management of Patients With Diabetes

View Set

Chapter 15 International Trade and Finance

View Set

Business Communication: Chapter 4

View Set

Brannigans's building construction for the fire service

View Set

DBMS Chapter 4: Logical Database Design and the Relational Model

View Set