Developing Algorithms Using Arrays

AP Computer Science A· difficulty 3/5

public static String findOwner(String[] names, int[] ids, int target) {
    for (int i = 0; i < ids.length; i++) {
        if (ids[i] == target) {
            return names[target];
        }
    }
    return "";
}

What is the bug?

  • A

    names[target] should be names[i] to use the same index

    check_circle
  • B

    The loop should iterate names.length

  • C

    target should be a String

  • D

    Nothing is wrong

Explanation

With parallel arrays, the same index i ties name to id. Using target as an index is unrelated to position and may even be out of bounds.

Want 10 more like this — adaptive to your weak spots?

Related questions