The main problem seems to be the increment that is not occurring. At the moment you are adding to count
own count
which is initially worth 0, so it will never come out of this value. The auto-addition operator must be used with values that are not neutral, otherwise the value will not be changed. Even if it started with 1, the count would progress geometrically, which is not what is desired, each step should always add up to 1 and not the last count. It’s simpler than this, just use the increment operator that equals doing count += 1
.
Another change I would make for performance issues is to take the character instead of the substring:
private int countVirgulas(String parametro) {
int count = 0;
for (int i = 0; i < parametro.length(); i++) {
if (parametro.charAt(i) == ',') {
count++;
}
}
return count;
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Or if you prefer:
private int countVirgulas(String parametro) {
int count = 0;
for (char caractere : parametro.toCharArray()) {
if (caractere == ',') {
count++;
}
}
return count;
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
If you want to use the substring()
has to make a mistake, since he’s not taking one character at a time:
private int countVirgulas(String parametro) {
int count = 0;
for (int i = 0; i < parametro.length(); i++) {
if (parametro.substring(i, i + 1).equals(",")) {
count++;
}
}
return count;
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Thanks bigown, in my case with the substring was not even entering the if and then I saw that put Count += Count and that was to use the Count++, using charAt(i) worked properly, thank you very much.
– Arthur Rodrigues