1 package JSci.chemistry; 2 3 import java.util.Collections ; 4 import java.util.HashSet ; 5 import java.util.Set ; 6 import JSci.physics.*; 7 8 13 public class Molecule extends Particle { 14 17 private final Set atoms = new HashSet (); 18 21 public Molecule(String formula) { 22 if(formula == null || formula.length() == 0) 23 throw new IllegalArgumentException ("Formula cannot be null or empty."); 24 int startPos = 0, endPos; 25 boolean isNumber = false; 26 String symbol = null; 27 int count; 28 for(int i=1; i<formula.length(); i++) { 29 char ch = formula.charAt(i); 30 if(Character.isUpperCase(ch)) { 31 endPos = i; 32 if(isNumber) { 33 count = Integer.parseInt(formula.substring(startPos, endPos)); 34 isNumber = false; 35 } else { 36 symbol = formula.substring(startPos, endPos); 37 count = 1; 38 } 39 String name = PeriodicTable.getName(symbol); 40 if(name != null) { 41 Element element = PeriodicTable.getElement(name); 42 for(int j=0; j<count; j++) 43 atoms.add(new Atom(element)); 44 } 45 startPos = endPos; 46 } else if(!isNumber && Character.isDigit(ch)) { 47 isNumber = true; 48 endPos = i; 49 symbol = formula.substring(startPos, endPos); 50 startPos = endPos; 51 } 52 } 53 endPos = formula.length(); 54 if(isNumber) { 55 count = Integer.parseInt(formula.substring(startPos, endPos)); 56 isNumber = false; 57 } else { 58 symbol = formula.substring(startPos, endPos); 59 count = 1; 60 } 61 String name = PeriodicTable.getName(symbol); 62 if(name != null) { 63 Element element = PeriodicTable.getElement(name); 64 for(int j=0; j<count; j++) 65 atoms.add(new Atom(element)); 66 } 67 } 68 71 public Molecule(Atom a, Atom b) { 72 atoms.add(a); 73 atoms.add(b); 74 } 75 78 public Molecule(Atom a[]) { 79 for(int i=0; i<a.length; i++) 80 atoms.add(a[i]); 81 } 82 85 public Set getAtoms() { 86 return Collections.unmodifiableSet(atoms); 87 } 88 92 public Molecule bind(Atom a) { 93 atoms.add(a); 94 return this; 95 } 96 100 public Molecule bind(Molecule m) { 101 atoms.addAll(m.atoms); 102 return this; 103 } 104 } 105 106 | Popular Tags |