import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Stack;
/**
* Created by mridul on 8/1/16.
*/
public class MolecularWeightComputer {
private interface Name<T>{
T getName();
void setName(T t);
}
private enum Atom{
Oxygen("O",15.9994F),
Carbon("C",12.011F),
Nitrogen("N",14.00674F),
Sulfur("S",32.066F),
Hydrogen("H",1.00794F);
private String symbol;
private float atomicWeight;
Atom(String symbol, float atomicWeight){
this.symbol=symbol;
this.atomicWeight=atomicWeight;
}
String getSymbol(){
return symbol;
}
float getAtomicWeight(){
return atomicWeight;
}
}
private static class Molecule implements Name<String>{
private String name;
private final String formula;
private float molecularWeight;
private Map<String,Integer> composition=new LinkedHashMap<>();
private Molecule(String formula){
this.formula = formula;
}
static Molecule createMoleculeFromFormula(String formula){
return new Molecule(formula.toUpperCase());
}
private float getMolecularWeight(){
return molecularWeight;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
private void computeAtomicCount(){
Stack<Integer> digits =new Stack<>();
String key="";
for(int index = 0; index< formula.length(); index++){
Character token= formula.charAt(index);
if(Character.isAlphabetic(token)){
key=Character.toString(token);
digits.clear();
}else if(Character.isDigit(token)){
int value=Integer.parseInt(Character.toString(token));
if(!digits.isEmpty()){
value=(digits.pop()*10)+value;
}
digits.push(value);
}
if(composition.containsKey(key)){
composition.put(key,digits.peek());
}else {
composition.put(key, 0);
}
}
//replace zero entries with one
for(Map.Entry<String,Integer> entry: composition.entrySet()){
if(entry.getValue()==0){
entry.setValue(1);
}
}
//print map values
for(Map.Entry<String,Integer> entry: composition.entrySet()){
System.out.printf("%s:%d ",entry.getKey(),entry.getValue());
}
System.out.println("\n");
}
private void computeMolecularWeight(){
computeAtomicCount();
float molecularWeight=0.0F;
for(Map.Entry<String,Integer> entry: composition.entrySet()){
for(Atom atom:Atom.values()){
if(entry.getKey().equalsIgnoreCase(atom.getSymbol())){
molecularWeight+=entry.getValue()*atom.getAtomicWeight();
}
}
}
this.molecularWeight=molecularWeight;
System.out.printf("Molecular weight of is %.2f%n", molecularWeight);
}
}
public static void main(String... args) {
System.out.printf("Leucine Data: %n");
Molecule leucine = Molecule.createMoleculeFromFormula("C6H13NO2");
leucine.computeMolecularWeight();
System.out.printf("Lysine Data: %n");
Molecule lysine = Molecule.createMoleculeFromFormula("C6H14N2O2");
lysine.computeMolecularWeight();
System.out.printf("Molecular difference is %.2f%n", leucine.getMolecularWeight() - lysine.getMolecularWeight());
}
}
Thursday, August 4, 2016
MolecularWeightComputer
Subscribe to:
Posts (Atom)