The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
![]() |
Home ![]() ![]() |
||
See also: Counting | ||
![]() ![]() ![]() ![]() ![]() ![]() ![]() |
||
Looping and Counting
The following program counts the number of times the letter 'a' appears in a string: int length = fruit.length(); int count = 0; int index = 0; while (index < length) { if (fruit.charAt(index) == 'a') { count = count + 1; } index = index + 1; } System.out.println (count); This program demonstrates a common idiom, called a counter. The variable count is initialized to zero and then incremented each time we find an 'a' (to increment is to increase by one; it is the opposite of decrement, and unrelated to excrement, which is a noun). When we exit the loop, count contains the result: the total number of a's. As an exercise, encapsulate this code in a method named countLetters, and generalize it so that it accepts the string and the letter as arguments. As a second exercise, rewrite the method so that it uses indexOf to locate the a's, rather than checking the characters one by one.
|
||
Home ![]() ![]() |