1

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]);
            }
        }
    }

}
1
  • What's not working? What happens when you run your code? What output/results are you seeing? Commented Dec 12, 2015 at 14:36

2 Answers 2

1

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]);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Even with variable e there im still getting nothing - print doesn't give anything run: BUILD SUCCESSFUL (total time: 0 seconds)
@vlad You need to replace towns[i].length() with towns.length() in the outer loop. I assume it's a typo, though.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.