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;
}
-
(1 point) Why does the method not return the correct value?
-
(1 point) What specific stylistic choice is the cause of the problem?
-
(1 point) Rewrite the method to return the correct result. Remove unnecessary variables and convert the
while
loop to afor
loop. -
(1 point) Write a method which, given a
String
, returnstrue
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 beboolean 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 thecountMatchingChars
method you wrote above.)