1

I'm having trouble writing a method that takes a string and counts the number of times the first character (or really any character) appears. The code I've written is below, but for some reason keeps returning half the correct count when I run it. Any help would be appreciated, thanks.

public static void countOccurrences(String string1) {
    int counter = 0;
    char toCheck = string1.charAt(0);
    char compareChar;
    for (int i = 0; i < string1.length(); i++) {
        compareChar = string1.charAt(i);
        if (toCheck == compareChar) {
            counter++;
        }
        i++;
    }
    System.out.println(toCheck + " appears " + counter + " times in string1.");
}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Ron A
  • 15
  • 3
  • Thank you everybody for you help. I completely spaced on the i in the for loop header already incrementing the variable (new to this), and that makes total sense! – Ron A Jul 31 '15 at 14:57

3 Answers3

3

You're incrementing i twice in each iteration, so you are skipping half the characters:

for (int i = 0; i < string1.length(); i++) { // i is incremented here

  compareChar = string1.charAt(i);
  if (toCheck == compareChar){
      counter++ ;
  }
  i++ ; // i is incremented again here - remove this line

}
Eran
  • 387,369
  • 54
  • 702
  • 768
0

Your immediate problem is that i++; happens twice per iteration.

An alternative approach is to use

s.length() - s.replace("x", "").length()

which gives you the number of times "x" appears in s. Arguably it's not the most efficient way, but it's clear.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

i++ in for loop is incrementing the i value by 1, no need to increment inside th eloop

check Working of For loop here

  public static void countOccurrences(String string1) {

  int counter = 0;

  char toCheck = string1.charAt(0);

  char compareChar;

  for (int i = 0; i < string1.length(); i++) { 

      compareChar = string1.charAt(i);
      if (toCheck == compareChar){
          counter++ ;
      }
  }
  System.out.println(toCheck + " appears " + counter + " times in string1.");
}
rhitz
  • 1,892
  • 2
  • 21
  • 26