Question 1 : Why does the method not return the correct value? Q 2 : What specif
ID: 3784901 • Letter: Q
Question
Question 1 : Why does the method not return the correct value?
Q 2 : What specific stylistic choice is the cause of the problem?
Q 3 : fix the while loop in that it works. Thank you
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+=1;
i++;
if (isMatched==true)
return count;
else
return 0;
}
Explanation / Answer
//Tested on Eclipse
/************************CharCount.java*************************/
public class CharCount {
static int countMatchingChars(String string, char toMatch) {
// variable declarations
int count = 0;
boolean isMatched = false;
int i = 0;
/**
* in loop we are checking if specific character is matching with
* toMatch character if its match then we increase count to 1
* */
while (i < string.length()) {
if (string.charAt(i) == toMatch) {
isMatched = true;
count += 1;
}
i++;
}
if (isMatched == true) {
return count;
} else {
return 0;
}
}
public static void main(String[] args) {
// calling method
int count = CharCount.countMatchingChars("Hello world", 'l');
System.out.println("Count of matched Character is " + count);
}
}
/******************output*******************/
Count of matched Character is 3
Thanks a lot
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.