循环不会多次迭代 if 语句



因此,我试图用这段代码解决的原始问题是获取一个不同长度的字符串,然后仅当该字符串包含 1-3 个"e"并且返回 false 时才返回 true。我想从给定的字符串中单独提取"e"并将它们放入单独的字符串中,然后测试新字符串必须产生正确的布尔值的"e"数量。隔离 pol 执行,通过将 3 个"e"放入空字符串中,我发现代码对于至少具有 1 e 的所有内容都返回 false。那里没有错,但后来我用 2 个"e"替换了空字符串,发现任何至少有 1 e 的东西都返回 true,即使该字符串总共包含 50 个"e"。这意味着循环在遇到 if 语句时只迭代一次,因此只向 String pol 添加了 1 e。我的首要问题是:如何让循环根据控件迭代 if 语句。

也不要担心这段代码之前的内容:只知道这是布尔值

String pol = "";
String some;
for (int len = 0; len < str.length(); len = len + 1) {
some = str.substring(len, len + 1);
if (some.equals("e")) {
pol = "" + some; 
}
}
if (pol.equals("e") || pol.equals("ee") || pol.equals("eee")) 
return true;
return false; 

每当你遇到一个e时,你都会覆盖pol而不是附加到它。而不是

pol = "" + some;

你可能的意思是:

pol += some;

无论如何,附加到字符串似乎是完成此任务的笨拙方法。每次遇到e时增加一个整数计数器会容易得多。或者使用 Java 8 的流更简单:

long count = str.chars().filter(c -> c == 'e').count();
return count >= 1 && count <= 3;

如果我理解正确,您想查看特定字符串中有多少个 'e。 有一种非常简单的方法可以做到这一点,称为增强型 for 循环。 使用这种循环,您可以在很少的行中做到这一点:

String s = "Hello There!";
int numOfEs = 0;
boolean bool = false; 
// loops through each character in the string s ('H', 'e', 'l', etc)
for (Character c : s.toCharArray() /* Make String s a list of characters to iterate through*/) {
if (c.equals('e') || c.equals('E')) // Make Uppercase and Lowercase Es both count 
numOfEs++;
}
// Are there 3 or more E's?
// If there aren't, the boolean will be false because I defined it to equal false.
if (numOfEs >= 3)
bool = true;
System.out.println(bool + ": There are " + numOfEs + " e's.");

poll = "" + some所做的只是将e放在投票中。试试poll = poll + some

最新更新