Atom.java:


public class Atom
{
    private String symbol;
       
    private int number;
       
    private float weight;
       
    public Atom(String symbol, int number, float weight)
    {
        this.symbol = symbol;
        this.number = number;
        this.weight = weight;
    }

    public String getSymbol()
    {
        return symbol;
    }

    public float getWeight()
    {
        return weight;
    }

    public int getNumber()
    {
        return number;
    }
}
 

Molecule.java:


import java.util.HashMap;
import java.util.Scanner;
import java.util.Map;
import java.util.Set;

public class Molecule
{
    private HashMap<Atom,Integer> atomMap;
       
    public Molecule()
    {
        atomMap = new HashMap<Atom,Integer>();
    }

    public Set<Atom> getAtoms()
    {
        return atomMap.keySet();
    }

    public int getRatio(Atom atom)
    {
        return atomMap.get(atom);
    }

    public void parse(PeriodicTable table, String molecularFormula)
    {
        Scanner scanner = new Scanner(molecularFormula);
        while (true)
        {
            String symbol = scanner.findInLine("[a-zA-Z]+");
            String ratio = scanner.findInLine("\\d+");
       
            if (symbol == null)
            {
                break;
            }
       
            int i = 1;
            if (ratio != null)
                i = Integer.parseInt(ratio);
       
            Atom atom = table.getAtom(symbol);
            atomMap.put(atom, i);
        }
    }

    public float getMass()
    {
        float mass = 0;
        for (Map.Entry<Atom, Integer> entry : atomMap.entrySet())
        {
            mass += entry.getValue() * entry.getKey().getWeight();
        }
   
        return mass;
    }
}
 

PeriodicTable.java:


import java.util.ArrayList;

public class PeriodicTable
{
    private ArrayList<Atom> atoms;
       
    public PeriodicTable()
    {
        atoms = new ArrayList<Atom>();
    }

    public void addAtom(Atom atom)
    {
        atoms.add(atom);
    }

    public Atom getAtom(String symbol)
    {
        for (Atom atom : atoms)
        {
            if (symbol.equals(atom.getSymbol()))
            {
                return atom;
            }
        }
   
        return null;
    }
}
 

UnitTester.java:


import org.junit.*;

public class UnitTester
{
    @Test
    public void testAtomConstructor()
    {
        Atom atom = new Atom("C", 6, 12.01f);
        Assert.assertTrue(atom.getSymbol().equals("C"));
        Assert.assertTrue(atom.getNumber() == 6);
        Assert.assertTrue(atom.getWeight() == 12.01f);
    }
}