Below is the syntax highlighted version of MolecularWeight.java
from §4.4 Symbol Tables.
/****************************************************************************** * Compilation: javac MolecularWeight.java * Execution: java MolecularWeight * Dependencies: ST.java StdIn.java elements.txt * * Reads in a list of elements and their molecular weights. * Prompts the user for the molecular description of a chemical * formula and prints out its molecular weight. * * % java MolecularWeight * H2.O * Molecular weight of H2.O = 18.020000 * N.H4.N.O3 * Molecular weight of N.H4.N.O3 = 80.060000 * ******************************************************************************/ public class MolecularWeight { public static void main(String[] args) { // symbol table whose key = element symbol and value = molecular weight ST<String, Double> st = new ST<String, Double>(); // read in elements symbols and their atomic weights In in = new In("elements.csv"); while (in.hasNextLine()) { String line = in.readLine(); String[] fields = line.split(","); String symbol = fields[2]; double weight = Double.parseDouble(fields[3]); st.put(symbol, weight); } // read in chemical formulas from stdin, and print out molecular weight while (StdIn.hasNextLine()) { double total = 0.0; String line = StdIn.readLine(); String[] fields = line.split("\\."); // period is a special regexp char for (int i = 0; i < fields.length; i++) { // parse Si5 into element and number of atoms int j; for (j = 0; j < fields[i].length(); j++) { if (Character.isDigit(fields[i].charAt(j))) break; } String symbol = fields[i].substring(0, j); double weight = st.get(symbol); // add weight to running total String atoms = fields[i].substring(j, fields[i].length()); if (atoms.length() == 0) total += weight; else total += Integer.parseInt(atoms) * weight; } StdOut.printf("Molecular weight of %s = %f\n", line, total); } } }