ZolloKaptain
ZolloKaptain

Reputation: 23

Loop doesn't iterate an if statement more than once

So, the original problem that I am attempting to solve with this code is taking a string of varying length and then returning true only if that string contains between 1-3 "e's" and if there are any less or more return false. I wanted to individually extract the "e's" from the the given Strings and put them into a separate String and then test for how many "e's" that new String has to produce the correct Boolean values. Isolating the pol execution, by putting 3 "e's" into the empty string, I found that the code was returning false for everything that had at least 1 e. Nothing wrong there, but then I replaced the empty string with 2 "e's" and found that anything with at least 1 e was returning true, even if that String contained 50 "e's" in total. This means that the loop, when encountering the if statement, only iterates once and so only 1 e is added to String pol. My overarching question is: How do I get the loop to iterate the if statement according to the control.

Also don't worry about what comes before this code: Only know that this is Boolean

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; 

Upvotes: 0

Views: 211

Answers (3)

Orion31
Orion31

Reputation: 596

If I understand you correctly, you would like to see how many 'e's are in a specific string. There is a very simple way to do this called an Enhanced for loop. Using this kind of loop, you can make this in very few lines:

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

Upvotes: 1

Mureinik
Mureinik

Reputation: 311188

Whenever you encounter an e you overwrite pol instead of appending to it. Instead of

pol = "" + some;

You probably meant:

pol += some;

Regardless, appending to a string seems like a clunky way of accomplishing this task. It would be much easier to just increment an integer counter each time you encounter an e. Or even simpler with Java 8's streams:

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

Upvotes: 2

gst1502
gst1502

Reputation: 306

All poll = "" + some does is put e in poll. Try poll = poll + some

Upvotes: 0

Related Questions