02: Control Flow

Submit this homework using Gradescope. You can type up your answers, or write legibly and scan them. Do not attempt to submit a paper copy in class, as it will not be accepted.


Consider the following method, which is trying to count the number of characters matching a specific character in a String:

int countMatchingChars(String string, char toMatch) {
  int count = 0;
  boolean isMatched = false;

  int i = 0;
  while (i < string.length())
    if (string.charAt(i) == toMatch)
      isMatched = true;
      count++;
    i++;

  if (isMatched)
    return count;
  else
    return 0;
}
  1. (1 point) Why does the method not return the correct value?

  2. (1 point) What specific stylistic choice is the cause of the problem?

  3. (1 point) Rewrite the method to return the correct result. Remove unnecessary variables and convert the while loop to a for loop.

  4. (1 point) Write a method which, given a String, returns true if and only if the count of the number of times the lowercase ‘a’ appears in the string is divisible by 7. The method’s signature should be boolean aCountDivisibleBySeven(String string). Reminder: you can use the modulus operator % to get the remainder of an integer division. For example, five divided by three is one, with a remainder of two. Java knows this too: (5 / 3 == 1) and (5 % 3 == 2). (Yes, you can refer to the countMatchingChars method you wrote above.)