我正在编写一个遍历字符串并在恰好找到两个“a”字符时返回 true 的方法。显然,并非所有条件都得到满足,但我找不到解决方法。该问题指出必须满足 boolean 类型。但是,在循环内部,如果在一次迭代中没有找到 a,则什么也不会发生。我该如何解决这个问题?
import java.util.*;
import static java.lang.System.out;
public static void main(String[] args) {
}
public static boolean hasTwoA(String s) {
int aCounter = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'a') {
aCounter++;
} else if (aCounter == 2) {
return true;
} else if (i == s.length() - 1 && aCounter != 2) {
return false;
}
}
}
}
最佳答案
这样写会更整洁:
int aCounter = 0;
for (int i = 0; i < s.length() && aCounter <= 2; ++i) {
if (s.charAt(i) == 'a') ++aCounter;
}
return aCounter == 2;
关于java - 如何使用方法在java中的字符串中查找两个 'a'字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35903655/