The problem is that your first if
does not cover the second.
The way it is (indenting correctly):
for (int i=0; i<text.length()-1; i++) {
if (text.charAt(i)==c)
count=count+1;
if(count==n)
index= i;
}
Will make the if(count==n)
is executed, whether or not it is in the right letter.
Imagining the search for the letter a
and n
to 1
begins with:
- Catch the first
a
of String
in position 7
- Alter
count
for 1
- Update the
index
because count
is equal to n
- The next letter is no longer
a
but the count
continues to 1
, then updates the index
for 8
wrongly. It will continue to update to the following letters until the count
increase again or String
finish.
Solve this easily with {}
, including the second if
in the first:
for (int i = 0; i < text.length() - 1; i++) {
if (text.charAt(i) == c) { //abre aqui
count = count + 1;
if (count == n)
index = i;
} //fecha aqui incluindo o outro if
}
So only when the letters are equal is there possibility of updating the index
.
Once the position is found it is no longer useful to do any other processing. For this reason can still improve the method by moving the return directly into the if
:
int buscaChar(String text, char c, int n) {
int count = 0;
for (int i = 0; i < text.length() - 1; i++) {
if (text.charAt(i) == c) {
count = count + 1;
if (count == n)
return i; //apenas return
}
}
return -1; //retorna -1 quando não existe
}
This way your code not only does not do unnecessary processing, but becomes even simpler.
Also note how I changed the return value when it does not exist to -1
, which is a universal value for this type of functions. This change of Returns has caused the variable index
wasn’t even necessary.
See this code working on Ideone
Note that to have the 40
which you have indicated must be the 4th a
and not the 5th because the first is capitalized and therefore does not count.
Thanks! Now it worked!
– find83