vlad
vlad

Reputation: 159

Finding matching strings in a String array

I'm having trouble extracting the names that contain more than 3 "O" or "o" in them from a string array. I have to print them after. Where did I go wrong and how can I fix it?

static String[] towns = {"England", "France",
    "Romania", "Germany", "Canada", "Russia",
      "Eoeoeooero"};

 public static void main(String[] args) {


    for (int i = 0; i < towns[i].length(); i++) {



            for (int j = 0; j < towns[i].length(); j++) {
                if (towns[i].charAt(j) == 'o' || towns[i].charAt(j) == 'O') {
                    e++;
                }
            }

            if (e > 3) {
                System.out.println(towns[i]);
            }
        }
    }

}

Upvotes: 1

Views: 1538

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

Since you are missing the declaration of variable e, I assume that it is declared in the scope of the class. This is a bad idea, because it becomes shared among all methods running on the same instance, or among all methods if it is static.

Make variable e local to your method, and move it into the scope of your for loop to fix the problem:

for (int i = 0; i < towns.length(); i++) {
    int e = 0; // <<== Here
    for (int j = 0; j < towns[i].length(); j++) {
        if (towns[i].charAt(j) == 'o' || towns[i].charAt(j) == 'O') {
            e++;
        }
    }
    if (e > 3) {
        System.out.println(towns[i]);
    }
}

Upvotes: 1

Barna Danko
Barna Danko

Reputation: 11

You have an uninitialized variable "e", which can cause a compile time error.

Also your first for loop for (int i = 0; i < towns[i].length(); i++) should be going through the elements of String[] towns, but what you wrote is using the length of a member of the array.

for (int i = 0; i < towns.length(); i++){
    int e = 0;
....

Upvotes: 0

Related Questions