RU beehive logo ITEC dept promo banner
ITEC 120
2019fall
asbrennem
ibarland

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.

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:

  1. 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.
  2. 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


logo for creative commons by-attribution license
This page licensed CC-BY 4.0 Ian Barland
Page last generated
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Rendered by Racket.