Molecules Exercise
for the SQT Lecture on Chapter 2
In this assignment, you will test the atoms method. The method returns the number of atoms of the given element inside the given molecule. You do not need to understand chemistry to do this assignment.
Molecules are represented by strings which contain elements (like "H" and "Na") and numbers. Here are some examples:
"H2O": twoHatoms and oneOatom"NaCl": oneNaatom and oneClatom"CH3CH2CH2CH3": fourCatoms and tenHatoms
Note the following:
- An element can consist of one uppercase letter (like
"H") or one uppercase and one lowercase letter (like"Na"). - A number after an element indicates multiple atoms of the same element. For example,
"H3"means threeHatoms, and"Na2"means twoNaatoms. The number is a single digit between 2 and 9 (inclusive). - An element that is not followed by a number, stands for a single atom of that element.
- An element may appear in the molecule multiple times, like in
"CH3CH2CH2CH3".
If either the element or the molecule is not in the given format, an IllegalArgumentException is thrown.
In the strings that you test with, you only have to consider letters and numbers in the ASCII range. So the only characters you have to consider are in the ranges 'a' to 'z', 'A' to 'Z', and '0' to '9' (no spaces, punctuation, etc.).