Loop Example

Here is a Codingbat-style loop problem along with a possible solution:

    /**
     * Return the number of times the strings "bug" or "rat" appear in the
     * provided string.
     */
    public static int countVermin3(String str) {
        int count = 0;
        String cur; // The current substring being examined.

        for (int i = 0; i < str.length() - 2; i++) {
            cur = str.substring(i, i + 3);
            if (cur.equals("bug") || cur.equals("rat")) {
                count++;
            }
        }
        return count;
    }

This solutions raises some questions:

Q. Why is the condition in the for loop i < str.length() - 2?

A. Each time through the loop, i will represent the starting position of the substring that will be compared to "bug" and "rat". We can't let i get all the way to the final index in the string! If we did, our call to substring, str.substring(i, i + 3), would be requesting characters that don't exist int the string. The condition is i < str.length() - 2 because we need i to stop two positions before the end of the string: the substring needs to include the character at the index, and the two following characters.

Q. Why create the cur variable? We could have done this instead:

            if (str.substring(i, i + 3).equals("bug") || 
                str.substring(i, i + 3).equals("rat")) {
                count++;
            }

A. The substring call, str.substring(i, i + 3) is a bit complicated. As much as possible, we want to avoid repeating complex chunks of code. Also, storing the substring in a local variable makes it easier to use the debugger or print statements to debug the code.

Q. Why is it cur.equals("bug") and not cur == bug?

A. In general, == only makes sense for primitive variables. String is a reference type. This means that == will actually compare the Strings locations in memory, it won't compare the contents of the strings.