-
-
Save hkkcngz/0c8975b0475559678e339641c8324777 to your computer and use it in GitHub Desktop.
Error spotting practice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
class Errors | |
{ | |
/* Adds the given value to everything in the ArrayList. | |
* | |
* This AddToAll method does not work correctly. Explain | |
* why. | |
* | |
* Which of the following replacements for line 19 will fix the method? | |
* (A) item = item + value; | |
* (B) int temp = item; | |
* item = temp + value; | |
* (C) while (item < value) item++; | |
* (D) Both A and B | |
* (E) None of the above | |
**/ | |
public void addToAll(ArrayList<Integer> items, int value) { | |
for (int item : items) { | |
item += value; | |
} | |
} | |
/* This sort method does not work correctly. What best | |
* describes what happens instead? | |
* | |
* (A) The list is sorted from largest to smallest | |
* instead of smallest to largest. | |
* (B) The smallest item is moved to the front of the list. | |
* (C) The smallest item is moved to the back of the list. | |
* (D) The list is randomly shuffled. | |
* (E) There will be an IndexOutOfBoundsException. | |
*/ | |
public void sort(ArrayList<Integer> items) { | |
for (int i = 0; i < items.size(); i++) { | |
int smallestIndex = i; | |
for (int j = 0; j < items.size(); j++) { | |
if (items.get(j) < items.get(i)) { | |
smallestIndex = j; | |
} | |
} | |
int temp = items.get(i); | |
items.set(i, items.get(smallestIndex)); | |
items.set(smallestIndex, temp); | |
} | |
} | |
/* What will be the output of |mystery(arr)| if arr contains | |
* [0, 1, 2, 0, 0, 3, 5]? | |
* | |
* (A) [0, 1, 2, 0, 0, 3, 5] | |
* (B) [1, 2, 0, 3, 5] | |
* (C) [0, 1, 2, 0, 3, 5] | |
* (D) Empty list | |
* (E) There will be an IndexOutOfBoundsException. | |
*/ | |
public void mystery(ArrayList<Integer> input) { | |
int numItems = input.size(); | |
for (int i = 0; i < numItems; i++) { | |
if (input.get(i) == 0) { | |
input.remove(i); | |
i--; | |
} | |
} | |
} | |
/* When will |strRecur| terminate without error? | |
* | |
* (A) When s.length() > 15. | |
* (B) When s.length >= 15. | |
* (C) When s contains at least 15 '*' characters. | |
* (D) It will never terminate without error. | |
* (E) It will always terminate without error. | |
**/ | |
public void strRecur(String s) { | |
if (s.length() < 15) { | |
System.out.println(s); | |
} | |
strRecur(s + "*"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment