Homework 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 char
acters 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;
}
A. (1 point) Why does the method not return the correct value?
B. (1 point) What specific stylistic choice is the cause of the problem?
C. (1 point) Rewrite the method to return the correct result. Remove unnecessary variables and convert the while
loop to a for
loop.
D. (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)