home—info—lects—labs—exams—hws
D2L—tutor/PIs—zoom (snow day)
Object120 + its docs—java.lang docs—java.util docs
loops of loops
counting chars in a String[]
Write a function which takes in a String[] and a char,
and returns how many times that character occurs anywhere in the string-array.
-
Write test-cases first.
-
You should use a helper function, and not a nested-loop.
-
Your helper function should have test-cases too!
-
In this case, all our methods will be static
(only because Java doesn't let us add things to class String
(nor class String[], if that were even a thing).
Then, make your main print how many times 'e' occured
in any of the command-line-arguments passed to it, as well as the
number of qs.
Run your code from the command-line (Start » git-bash):
prompt> javac CharCounter.java
prompt> java CharCounter quicker elephant qqq
3 words contain 3 'e's and 4 'q's.
prompt> java CharCounter
0 words contain 0 'e's and 0 'q's.
N.B. If you want to re-print the words provided, feel free;
you can use the built-in static java.util.Arrays.toString.
Note that there is no Scanner at all, in this program.
Challenge task: histogram
Instead of counting the occurrences of just a single letter (using one int),
count the occurrences of each letter (using an int[] of size, say, 26 or perhaps 256).
You can either:
-
make a helper function which takes one String, returns a new array of counts,
and then combine those counts into an array of running-counts.
-
Make a helper function which takes one String and a counts-so-far,
and modifies that array to update the counts from that one string.
Remember that 'd'-'a' is int 3, and 'a'-'a' is the int 0.
java.lang.Character#toLowerCase
prompt> javac AllCharCounter.java
prompt> java AllCharCounter quicker elephant zzz
The 3 words [quicker,elephant,zzz] contain:
1 'a's
0 'b's
1 'c's
⋮
0 'z's
N.B. you can use the built-in static java.util.Arrays.toString.
Write test-cases first, of course!
Copy/pasting this might help, with an expected result:
new int[] {0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0}; // 26 zeros
home—info—lects—labs—exams—hws
D2L—tutor/PIs—zoom (snow day)
Object120 + its docs—java.lang docs—java.util docs
 This page licensed CC-BY 4.0 Ian Barland Page last generated | Please mail any suggestions (incl. typos, broken links) to ibarland radford.edu |
 |