The problem is that your first if
does not cover the second.
The way you are (indenting correctly):
for (int i=0; i<text.length()-1; i++) {
if (text.charAt(i)==c)
count=count+1;
if(count==n)
index= i;
}
It will make if(count==n)
run regardless of whether it is in the right letter or not.
Wondering what to search for the letter a
and n
a 1
begins with:
- Catch the first
a
of String
at 7
- Change% from% to% with%
- Refresh
count
because 1
equals index
- The next letter is no longer
count
but n
continues to a
, so it refreshes count
to 1
wrong. It will continue to update to the next few letters until index
increases again or 8
ends.
Solve this easily with count
, including the second String
on 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 can the {}
be updated.
Once found the position is no longer useful to do any other processing. For this reason you can further improve the method by moving the return directly into 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
}
In this way your code not only does not make unnecessary processing, it's even simpler.
Also note how I changed the return value when it does not exist for index
, which is a universal value for this type of function. This return exchange made the variable if
not even necessary.
See this code working on Ideone
Note that to have the -1
you indicated must be the 4th index
and not the 5th because the first is uppercase and therefore does not count.