In this studio, you will write a program to count the number of times each character occurs in a string and then print the results to the console.
Feel free to prompt the user for a string. However, for the sake of simplicity, you might want to start by hard-coding some text and storing it in a variable. For your convenience, here is a quote from the movie Hidden Figures:
If the product of two terms is zero then common sense says at least one of the two terms has to be zero to start with. So if you move all the terms over to one side, you can put the quadratics into a form that can be factored allowing that side of the equation to equal zero. Once you’ve done that, it’s pretty straightforward from there.
Tip
Remember, you can turn a String
object into an array of characters
using:
char[] charactersInString = myString.toCharArray();
ArrayList
, HashMap
, or Array
)
should you use to store character counts? Any can be made to work, but there
is a BEST choice.For the example string above, your output should look something like:
I: 1
O: 1
S: 1
’: 2
: 66
a: 20
b: 2
c: 7
d: 7
e: 32
f: 9
g: 2
h: 13
i: 11
l: 6
,: 2
m: 8
n: 12
.: 3
o: 31
p: 3
q: 3
r: 18
s: 16
t: 38
u: 8
v: 3
w: 5
y: 5
z: 3
Try these modifications on your code:
Read the string in from a file.
Note
This is a hard one. We won’t talk about reading from files in Java in this course, so be ready for a tough challenge if you accept this mission.