【问题标题】:Loop doesn't iterate an if statement more than once循环不会多次迭代 if 语句
【发布时间】:2017-10-02 22:02:40
【问题描述】:

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

【问题讨论】:

  • 应该是pol += some;?另外,请处理您的代码格式。您的原始代码格式非常糟糕,使其他人难以阅读和理解。我已经为你更正了,但我们不应该为你这样做。
  • 对不起,我才刚刚开始使用这个网站,它正在撕裂我的代码。另外,为什么会这样?
  • 因为您每次都将 pol 重新实例化为“e”。执行 += 会改为添加到字符串变量中的现有值。
  • 我明白了。谢谢各位!

标签: java string for-loop if-statement boolean-expression


【解决方案1】:

每当您遇到e 时,您覆盖 pol 而不是附加到它。而不是

pol = "" + some;

你的意思可能是:

pol += some;

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

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

【讨论】:

    【解决方案2】:

    如果我理解正确,您想查看特定字符串中有多少个 'e。有一种非常简单的方法可以做到这一点,称为Enhanced for loop。使用这种循环,您只需几行代码即可完成:

    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.");
    

    【讨论】:

      【解决方案3】:

      所有poll = "" + some 所做的都是将e 放入投票中。试试poll = poll + some

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-01
        • 2015-05-04
        • 1970-01-01
        • 2015-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多