The following code attempts to examine a String and return whether it contains a
ID: 3588362 • Letter: T
Question
The following code attempts to examine a String and return whether it contains a given letter. A flag named found is used. However, the Boolean logic is not implemented correctly, so the method does not always return the correct answer. In what cases does the method report an incorrect answer? Change the code so that it will always return a correct result. Revert Type your solution here: 1public static boolean contains (String str, char ch) ( 2 boolean found = false; for (int i = e; i str.length(); i++) { 4 if ((str.charAt(1) == ch )) { found = true; ) else f 6 7 8 9 found = false; 10 return found;Explanation / Answer
we are running for loop up to length of string. Let assume we found a character at position less then str length, that time found will be true but for next iteration it become false. so i have added break statement after founding character in string, so it will break the loop.
public static boolean contains(String str, char ch) {
boolean found = false;
for (int i = 0; i < str.length(); i++) {
if ((str.charAt(i) == ch)) {
found = true;
break;
} else {
found = false;
}
}
return found;
}
Please let me know, If you have any doubt.
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.