Search code examples
javavariablesif-statementinitialization

Where should I initialize a variable to work in an IF block?


I'm trying to solve this problem on CodingBat:

Return true if the given string contains between 1 and 3 'e' chars.

So far, I have this solution, but it won't compile if I have the "numofe" integer initialized inside the IF block, because other parts of the code won't work with it, and vice versa. So where should I initialize a variable, to be accessible everywhere in the code?

Thank you.

public boolean stringE(String str) {

  int numofe;

  for(int x = 0; str.length() > x; x++){

    if (str.charAt(x)=='e'){

      numofe++;
    }

  }
   return (numofe>0 && numofe<4);
}

Solution

  • Variables within a block should be initialized before you use them, initialize them with an initial value , it could be any allowed value. but you can not use them without first initialize them.

    int numofe=0;
    

    This will not compile numofe++;, because numofe is not initialized in your code