CSC 221: Computer Programming I
Fall 2005

Test 2 Review Questions


  1. What is output by the following code segment?

    int n = 4, p = 1; while (n > 0) { p *= n; n--; System.out.println(p); }

  2. Rewrite the following while loop as a for loop.

    int value = 10; while (value < 1000) { System.out.println(value); value *= 2; }

  3. Suppose you have been given the Die class described in lectures. Recall that the Die class has the following methods: roll, getNumberOfSides, and getNumberOfRolls.

  4. Consider the following static method.

    public static String mystery(String str1, String str2) { String copy = ""; int index = 0; while (index < str1.length() && index < str2.length()) { copy += str1.charAt(index) + str2.charAt(index); index++; } return copy; }

    What would be returned by each of the following method calls?

  5. Describe in concise English the purpose of the following method. That is, when called with an aribtrary ArrayList of words, what does the method do?

    public void doSomething(ArrayList<String> words) { for (int i = words.size()-1; i >= 0; i--) { String entry = words.get(i); System.out.println(entry); } }

  6. Complete the definition of the numOccurrences method below, which takes an ArrayList of words and a desired word, and returns the number of times the desired word appears in the ArrayList.

    public static int numOccurrences(ArrayList<String> words, String desired) { }