JavaJoker204
JavaJoker204

Reputation: 83

Java: Problems in Changing for each loop to normal for loop in method

I have the following method and I wanted to change the for each loops to normal for loops. So I tried something like this

for (int i = 0; i < above.length(); i++) {
    char x = above.toCharArray();
    if (x == 'x') {
        counter++;
    }
}

But I know that's wrong. So, what's the right way to change these for each loops to normal for loops?

public static int neighbourconditions(String above, String same, String below){
    int counter = 0;
    if(above != null){
        for(char x : above.toCharArray()){
            if(x == 'x'){
                counter++;
            }
        }
    }
    for (char x : same.toCharArray()){
        if (x == 'x'){
            counter++;
        }
    }
    if (below != null){
        for(char x : below.toCharArray()){
            if (x == 'x'){
                counter++;
            }
        }
    }
    return counter;
}

Upvotes: 0

Views: 1233

Answers (4)

Amit Mahajan
Amit Mahajan

Reputation: 915

If you need to count occurances of character x then you may try below or a regex:

String upAbove = above.replaceAll("x","");
int count = above.length() - upAbove.length();

Upvotes: 1

omarioja
omarioja

Reputation: 11

I would imagine that you would have to find the length of each string being passed to the method. Example if the content of above is equal to "some_randome_string" you would have to find the length of the string or how many characters are in the string. in this case that would be 19. then you would do;

        if <variable != null > {
           for (x = 0; x < 18 ; x++) {
       code block to be executed
      } 
    }

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60046

You can use above.toCharArray().length and to get the value above.toCharArray()[i] and with collaboration with @chillworld:

You can create an array of char[] array = above.toCharArray(); outside the loop like this :

char[] array = above.toCharArray();
for (int i = 0; i < array.length; i++) {
    if (array[i] == 'x') {
        counter++;
    }
}

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522817

Just use a basic for loop whose bounds are governed by the length of the string, which is the same as the size of the corresponding character array, e.g. the first loop:

for (char x : above.toCharArray()) {
    if (x == 'x') {
        counter++;
    }
}

would become this:

for (int x=0; x < above.length(); ++x) {
    if (above.charAt(x) == 'x') {
        counter++;
    }
}

Upvotes: 5

Related Questions