String Methods

AP Computer Science A· difficulty 4/5

public static String run() {
    String s = "computer";
    StringBuilder sb = new StringBuilder();
    for (int i = s.length() - 1; i >= 0; i--) {
        if (i % 2 == 0) sb.append(s.charAt(i));
    }
    return sb.toString();
}
// Call: System.out.println(run());

What is printed?

  • A

    cpot

  • B

    rtmc

  • C

    etupc

  • D

    eumc

    check_circle

Explanation

"computer" indices: c(0),o(1),m(2),p(3),u(4),t(5),e(6),r(7). Iterating i from 7 down to 0 and only appending when i is even: i=6 e, i=4 u, i=2 m, i=0 c. Result "eumc".

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

Related questions