Header Ads Widget

Responsive Advertisement

Molecular weight of chemistry in Java code

 

 


You can calculate the molecular weight of a chemical compound in Java by summing the atomic masses of all atoms present in the compound. Here is a Java program that calculates the molecular weight based on a simple input string representing the chemical formula.

The code uses predefined atomic weights of common elements in a HashMap and processes the formula to compute the molecular weight.

Example Java Code to Calculate Molecular Weight:

package com.kartik;

import java.util.Enumeration;
import java.util.Hashtable;
import java.io.*;
/**
 *  it is for those who deal with all chemistry related subjects or students who are have a need
 *  to find an element's molecular weight. Molecular weight basically is the element's weight and
 *  the finding the expression full molecular weight.For Eg: H2O; in this case we can say that
 *  there are two Hydrogen atoms and 1 Oxygen atom so for the molecular weight calculation
 *  the expression would be say Hydrogen's atomic weight times 2 + Oxygen's atomic weight.
 *   Say for example the element Hydrogen has the atomic weight of 1 and oxygen has
 *   the atomic weight of 16. Then the expression result would be 1X2+16=18.
 *The following is the code for finding the molecular weight in Java:    
 * @author kartik
 * The following is the method  for finding the molecular weight in Java:

 */
public class ElementCalculation {
       static Hashtable hm;
       Hashtable[][]reactpro;
       Hashtable[] tempList;
       Hashtable brentry=new Hashtable();
       double output,finaloutput;
       int newId=0,roundOpen=0,boxOpen=0,fullLen=0,indexLen=0,hmRowpos=0,hmColpos=0,digitValue=0,tempIndex=0,suffix=0;
       String temp="",args="";
       boolean keyExists=false,yesno=false;
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       public ElementCalculation()
       {
             setInitialValues();
             initializeDefaultreactPro();
       }
    public void dispose()
    {
       temp = "";
       roundOpen = boxOpen = tempIndex = hmRowpos = hmColpos = digitValue = fullLen = indexLen = newId = suffix = 0;
       brentry.clear();
       keyExists=yesno=false;
       finaloutput = output = 0;
    }
       private static void setInitialValues()
       {
             hm=new Hashtable();
             hm.put("H", new Double(1.0079));
        hm.put("He", new Double(4.0026));
        hm.put("Li", new Double(6.941));
        hm.put("Be", new Double(9.0122));
        hm.put("B", new Double(10.811));
        hm.put("C", new Double(12.0107));
        hm.put("N", new Double(14.0067));
        hm.put("O", new Double(15.9994));
        hm.put("F", new Double(18.9984));
        hm.put("Ne", new Double(20.1797));
        hm.put("Na", new Double(22.9897));
        hm.put("Mg", new Double(24.305));
        hm.put("Al", new Double(26.9815));
        hm.put("Si", new Double(28.0855));
        hm.put("P", new Double(30.9738));
        hm.put("S", new Double(32.065));
        hm.put("Cl", new Double(35.453));
        hm.put("K", new Double(39.0983));
        hm.put("Ar", new Double(39.948));
        hm.put("Ca", new Double(40.078));
        hm.put("Sc", new Double(44.9559));
        hm.put("Ti", new Double(47.867));
        hm.put("V", new Double(50.9415));
        hm.put("Cr", new Double(51.9961));
        hm.put("Mn", new Double(54.938));
        hm.put("Fe", new Double(55.845));
        hm.put("Ni", new Double(58.6934));
        hm.put("Co", new Double(58.9332));
        hm.put("Cu", new Double(63.546));
        hm.put("Zn", new Double(65.39));
        hm.put("Ga", new Double(69.723));
        hm.put("Ge", new Double(72.64));
        hm.put("As", new Double(74.9216));
        hm.put("Se", new Double(78.96));
        hm.put("Br", new Double(79.904));
        hm.put("Kr", new Double(83.8));
        hm.put("Rb", new Double(85.4678));
        hm.put("Sr", new Double(87.62));
        hm.put("Y", new Double(88.9059));
        hm.put("Zr", new Double(91.224));
        hm.put("Nb", new Double(92.9064));
        hm.put("Mo", new Double(95.94));
        hm.put("Tc", new Double(98));
        hm.put("Ru", new Double(101.07));
        hm.put("Rh", new Double(102.9055));
        hm.put("Pd", new Double(106.42));
        hm.put("Ag", new Double(107.8682));
        hm.put("Cd", new Double(112.411));
        hm.put("In", new Double(114.818));
        hm.put("Sn", new Double(118.71));
        hm.put("Sb", new Double(121.76));
        hm.put("I", new Double(126.9045));
        hm.put("Te", new Double(127.6));
        hm.put("Xe", new Double(131.293));
        hm.put("Cs", new Double(132.9055));
        hm.put("Ba", new Double(137.327));
        hm.put("La", new Double(138.9055));
        hm.put("Ce",new Double(140.116));
        hm.put("Pr", new Double(140.9077));
        hm.put("Nd", new Double(144.24));
        hm.put("Pm", new Double(145));
        hm.put("Sm", new Double(150.36));
        hm.put("Eu", new Double(151.964));
        hm.put("Gd", new Double(157.25));
        hm.put("Tb", new Double(158.9253));
        hm.put("Dy",new Double(162.5));
        hm.put("Ho", new Double(164.9303));      
        hm.put("Er", new Double(167.259));
        hm.put("Tm", new Double(168.9342));
        hm.put("Yb", new Double(173.04));
        hm.put("Lu", new Double(174.967));
        hm.put("Hf", new Double(178.49));
        hm.put("Ta", new Double(180.9479));
        hm.put("W", new Double(183.84));
        hm.put("Re", new Double(186.207));
        hm.put("Os", new Double(190.23));
        hm.put("Ir", new Double(192.217));
        hm.put("Pt", new Double(195.078));
        hm.put("Au", new Double(196.9665));
        hm.put("Hg", new Double(200.59));
        hm.put("Tl", new Double(204.3833));
        hm.put("Pb", new Double(207.2));
        hm.put("Bi", new Double(208.9804));
        hm.put("Po", new Double(209));
        hm.put("At", new Double(210));
        hm.put("Rn", new Double(222));
        hm.put("Fr", new Double(223));
        hm.put("Ra", new Double(226));
        hm.put("Ac", new Double(227));
        hm.put("Pa", new Double(231.0359));
        hm.put("Th", new Double(232.0381));
        hm.put("Np", new Double(237));
        hm.put("U", new Double(238.0289));
        hm.put("Am", new Double(243));
        hm.put("Pu", new Double(244));
        hm.put("Cm", new Double(247));
        hm.put("Bk", new Double(247));
        hm.put("Cf", new Double(251));
        hm.put("Es", new Double(252));
        hm.put("Fm",new Double(257));
        hm.put("Md", new Double(258));
        hm.put("No", new Double(259));
        hm.put("Rf", new Double(261));
        hm.put("Lr", new Double(262));
        hm.put("Db", new Double(262));
        hm.put("Bh", new Double(264));
        hm.put("Sg", new Double(266));
        hm.put("Mt", new Double(268));
        hm.put("Rg", new Double(272));
        hm.put("Hs", new Double(277));
        hm.put("Ds", new Double(280));
       }
   
       //This function is created temporary to test the functinality in BBD
       private void initializeDefaultreactPro()
       {
             reactpro=new Hashtable[2][];
             reactpro[0]=new Hashtable[1];
             reactpro[1]=new Hashtable[1];
             initializeReactPro();
       }
       //For initializing the reactPro Hashtable
       private void initializeReactPro()
       {
             for(int i=0;i<reactpro.length;i++)

            {
                    for(int j=0;j<reactpro[i].length;j++)
                           reactpro[i][j]=new Hashtable();
             }
       }
       private boolean contains(String args){
             yesno=false;
             for(int i=0;i<args.length();i++)
             {
                    if(args.charAt(i)=='(' || args.charAt(i)=='[')
                    {
                           yesno=true;
                           break;
                    }
             }
             return yesno;
       }
       public void accept()
       {
             try
             {
                    System.out.println("Enter your expression");
                    args="H2So4";
                   // args=br.readLine();
                    if(contains(args)==true)
                           getNoOfBrackets(args);
                    reactpro[hmRowpos][hmColpos].clear();
                    calculateLength(args);
                    matchElementToUpdate(reactpro[hmRowpos][hmColpos],brentry);
                    calculateMolWeight(hmRowpos,hmColpos);
             }
             catch(Exception e1){}
       }
     
       //to calculate the no of Brackets appearing in the string
       private void getNoOfBrackets(String args)
       {
             for(int i=0;i<args.length();i++)
             {
                    if(args.charAt(i)=='(' || args.charAt(i)=='[')
                           tempIndex++;
             }
             tempList=new Hashtable[tempIndex];

             tempIndex=0;
             initializeTempHash();
       }
        /*intialized the templist hashtable*/
       private void initializeTempHash()
       {
             for (int i = 0; i < tempList.length; i++)
              tempList[i] = new Hashtable();
       }
       private void calculateLength(String args)
       {
             fullLen=args.length();
             indexLen=fullLen-1;
             readAtom(args);
       }
       //for calculating the next position within the String array.
       private int calculateNextPosition(int org)
       {
              int id = 0;
            if (org == fullLen - 1)
            {
               if (boxOpen > 0 || roundOpen > 0)
                    id = org;
                else
                   id = 0;
            }
            else if (org < fullLen - 1)
              id = org + 1;
           newId = id;
         return newId;
       }
        private void readAtom(String args) {
               for(int i=0,nxtpos=0;i<args.length();i++)
               {
                   temp="";
                   nxtpos=calculateNextPosition(i);
                  if(Character.isUpperCase(args.charAt(i))&& Character.isUpperCase(args.charAt(indexLen-(indexLen-nxtpos))))
                   {
                       temp=String.valueOf(args.charAt(i));
                       addentry(1);
                   }
                   else if(Character.isUpperCase(args.charAt(i)) && (args.charAt(indexLen-(indexLen-nxtpos))=='[' || args.charAt(indexLen-(indexLen-nxtpos))=='('))
                   {
                       temp = String.valueOf(args.charAt(i));
                       addentry(1);

                       if(args.charAt(indexLen - (indexLen - nxtpos))=='(')
                           roundOpen++;
                       else
                         boxOpen++;
                        // suffix = 1;
                       i=readBrackets(args, indexLen - (indexLen - nxtpos));
                   }
                   else if(Character.isUpperCase(args.charAt(i)) && Character.isDigit(args.charAt(indexLen-(indexLen-nxtpos))))
                   {
                       temp =String.valueOf(args.charAt(i));
                       //keyexists = reactpro[hmrpos][hmcpos].containsKey(temp);
                       i=IsDigit(args, indexLen - (indexLen - nxtpos));
                       addentry(digitValue);
                   }
                   else if(Character.isUpperCase(args.charAt(i)))
                   {
                       temp=String.valueOf(args.charAt(i));
                       i=readLower(args,i);
                       i=i-1;
                   }
                   else if(args.charAt(i)=='[')
                   {
                       boxOpen++;
                       if(!brentry.isEmpty())
                       {
                           addToTempHash();
                           tempIndex++;
                       }
                       i=readBrackets(args, i);
                   }
                   else if(args.charAt(i)=='(')
                   {
                       roundOpen++;
                       if(!brentry.isEmpty())
                       {
                           addToTempHash();
                           tempIndex++;
                       }
                       i=readBrackets(args, i);
                   }
               }
           }
           //This function is used for reading the elements having lower case letters and also for reading the digits
           private int readLower(String args, int idx) {
               for(int j=idx+1,nxtpos=0;j<args.length();j++)
               {
                   nxtpos=calculateNextPosition(j);
                    if(Character.isLowerCase(args.charAt(j))&& (!(Character.isDigit(args.charAt(indexLen-(indexLen-nxtpos))) || Character.isLowerCase(args.charAt(indexLen-(indexLen-
nxtpos))))))
                    {
                       temp+=String.valueOf(args.charAt(j));
                       if (roundOpen == 0 && boxOpen == 0)
                               addentry(1);
                       else
                       {
                           if (!brentry.isEmpty())
                           {
                              addToTempHash();
                              tempIndex++;
                           }
                           addentry(1);
                       }
                    }
                    else if(Character.isLowerCase(args.charAt(j)) && Character.isDigit(args.charAt(indexLen-(indexLen-nxtpos))))
                    {
                       temp+=String.valueOf(args.charAt(j));
                       j=IsDigit(args,indexLen-(indexLen-nxtpos));
                       addentry(digitValue);
                    }
                    else if(Character.isLowerCase(args.charAt(j))&& args.charAt(indexLen-(indexLen-nxtpos))=='[')
                    {
                        temp+=String.valueOf(args.charAt(j));
                        addentry(1);
                        boxOpen++;
                        //suffix=1;
                        addToTempHash();
                        tempIndex++;
                        j=readBrackets(args, indexLen-(indexLen-nxtpos));
                    }
                    else if(Character.isLowerCase(args.charAt(j))&& args.charAt(indexLen-(indexLen-nxtpos))=='(')
                    {
                        temp+=String.valueOf(args.charAt(j));
                        addentry(1);
                        roundOpen++;
                        //suffix=1;
                        addToTempHash();
                        tempIndex++;
                        j=readBrackets(args, indexLen-(indexLen-nxtpos));
                    }
                    else if(Character.isDigit(args.charAt(j))&& args.charAt(indexLen-(indexLen-nxtpos))==')')
                    {
                          j=IsDigit(args, j);
                       if(roundOpen>1)
                       {
                           keyExists=brentry.containsKey(temp);
                           if(keyExists)
                           {
                               suffix=digitValue;
                               j=IsDigit(args, indexLen-(indexLen-nxtpos)+1);
                               digitValue*=suffix;
                               suffix=0;
                               addentry(digitValue);
                               roundOpen--;
                           }
                           else
                               addentry(digitValue);
                       }
                       else
                           addentry(digitValue);
                    }
                    else if(Character.isDigit(args.charAt(j)) && args.charAt(indexLen-(indexLen-nxtpos))==']')
                    {
                         j=IsDigit(args, j);
                       if(boxOpen>1)
                       {
                           keyExists=brentry.containsKey(temp);
                           if(keyExists)
                           {
                               suffix=digitValue;
                               j=IsDigit(args, indexLen-(indexLen-nxtpos)+1);
                               digitValue*=suffix;
                               suffix=0;
                               addentry(digitValue);
                               boxOpen--;
                           }
                           else
                               addentry(digitValue);
                       }
                       else
                           addentry(digitValue);
                    }
                    else if(Character.isLowerCase(args.charAt(j)))
                    {
                        temp+=String.valueOf(args.charAt(j));
                        for(int k=j+1,nxtpos1=0;j<args.length();k++)
                        {
                            nxtpos1=calculateNextPosition(k);
                            if(Character.isLowerCase(args.charAt(k))&& !Character.isDigit(args.charAt(indexLen-(indexLen-nxtpos1))))
                            {
                               temp+=String.valueOf(args.charAt(k));
                               addentry(1);
                            }
                            else if(Character.isLowerCase(args.charAt(k)) && Character.isDigit(args.charAt(indexLen-(indexLen-nxtpos1))))
                            {
                               temp+=String.valueOf(args.charAt(k));
                               k=IsDigit(args, k);
                               addentry(digitValue);
                            }
                           else if(Character.isLowerCase(args.charAt(k))&& args.charAt(indexLen-(indexLen-nxtpos1))=='[')
                           {
                               temp+=String.valueOf(args.charAt(k));
                               addentry(1);
                               boxOpen++;
                               k=readBrackets(args, indexLen-(indexLen-nxtpos1));
                           }
                           else if(Character.isLowerCase(args.charAt(k))&& args.charAt(indexLen-(indexLen-nxtpos1))=='(')
                           {
                               temp+=String.valueOf(args.charAt(k));
                               addentry(1);
                               roundOpen++;
                               k=readBrackets(args, indexLen-(indexLen-nxtpos1));
                           }
                           else if(Character.isDigit(args.charAt(k)))
                           {
                               k=IsDigit(args, k);
                               addentry(digitValue);
                           }
                           else if(Character.isUpperCase(args.charAt(k)))
                           {
                               j=k-1;
                               break;
                           }
                           else
                           {
                               j=k-1;
                               break;
                           }
                        }
                    }
                    else if(Character.isDigit(args.charAt(j))&& args.charAt(indexLen-(indexLen-nxtpos))!=')')
                    {
                        j=IsDigit(args, j);
                        addentry(digitValue);
                    }
                    else if(Character.isUpperCase(args.charAt(j)))
                    {
                        newId=j;
                        break;
                    }
                    else if(args.charAt(j)=='[' && args.charAt(indexLen-(indexLen-nxtpos))=='(')
                    {
                        boxOpen++;
                        j=readBrackets(args, indexLen-(indexLen-nxtpos));
                    }
                    else if(args.charAt(j)=='[')
                    {
                        boxOpen++;
                        if(boxOpen>0)
                        {
                            if(!brentry.isEmpty())
                            {
                                addToTempHash();
                                tempIndex++;
                            }
                        }
                        j=readBrackets(args, j);
                    }
                    else if(args.charAt(j)=='(')
                    {
                        roundOpen++;
                        if(roundOpen>0)
                        {
                            if(!brentry.isEmpty())
                            {
                                addToTempHash();
                                tempIndex++;
                            }
                        }
                        j=readBrackets(args, j);
                    }
                    else if(args.charAt(j)==')' && Character.isDigit(args.charAt(indexLen-(indexLen-nxtpos))))
                    {
                        roundOpen--;
                        j=IsDigit(args, indexLen-(indexLen-nxtpos));
                        if(boxOpen==0 && roundOpen==0)
                        {
                            if(!brentry.isEmpty())
                            {
                                updateentry(brentry,digitValue);
                                tempIndex=tempIndex>0?tempIndex=tempIndex-1:0;
                                if(!tempList[tempIndex].isEmpty())
                                    matchElementToUpdate(this.brentry,this.tempList[tempIndex]);
                                else
                                {
                                    //suffix=0;
                                    addToReactPro();
                                }
                            }
                            else
                                updateentry(reactpro[hmRowpos][hmColpos],digitValue);
                       }
                       else
                       {
                           updateentry(brentry,digitValue);
                           tempIndex=tempIndex>0?tempIndex=tempIndex-1:0;
                           if(!tempList[tempIndex].isEmpty())
                               matchElementToUpdate(brentry, tempList[tempIndex]);
                           else                           {
                               //suffix=0;
                               addToReactPro();
                           }
                       }
                    }
                    else if(args.charAt(j)==']' && Character.isDigit(args.charAt(indexLen-(indexLen-nxtpos))))
                    {
                        boxOpen--;
                        j=IsDigit(args, indexLen-(indexLen-nxtpos));
                        if(boxOpen==0 && roundOpen==0)
                        {
                            if(!brentry.isEmpty())
                            {
                                updateentry(brentry,digitValue);
                                tempIndex=tempIndex>0?tempIndex=tempIndex-1:0;
                                if(!tempList[tempIndex].isEmpty())
                                    matchElementToUpdate(brentry,tempList[tempIndex]);
                                else
                                {
                                    //suffix=0;
                                    addToReactPro();
                                }
                            }
                            else
                                updateentry(reactpro[hmRowpos][hmColpos], digitValue);
                        }
                        else
                        {
                            updateentry(brentry,digitValue);
                            tempIndex=tempIndex>0?tempIndex=tempIndex-1:0;
                            if(!tempList[tempIndex].isEmpty())
                                matchElementToUpdate(this.brentry,this.tempList[tempIndex]);
                            else
                            {
                                suffix=0;
                                addToReactPro();
                            }
                        }
                    }
                    else if(args.charAt(j)==')')
                    {
                        roundOpen--;
                        if(roundOpen==0 && boxOpen==0)
                            addToReactPro();
                        else
                        {
                            tempIndex=tempIndex>0?tempIndex=tempIndex-1:0;
                            if(!tempList[tempIndex].isEmpty())
                                matchElementToUpdate(brentry,tempList[tempIndex]);
                            else
                            {
                                suffix=0;
                                addToReactPro();
                            }
                        }
                    }
                    else if(args.charAt(j)==']')
                    {
                        boxOpen--;
                        if(roundOpen==0 && boxOpen==0)
                            addToReactPro();
                        else
                        {
                            tempIndex=tempIndex>0?tempIndex=tempIndex-1:0;
                            if(!tempList[tempIndex].isEmpty())
                                matchElementToUpdate(brentry,tempList[tempIndex]);
                            else
                            {
                                suffix=0;
                                addToReactPro();
                            }
                        }
                    }
                    newId=j;
               }
               return newId;
           }
           //For reading the brackets expression
           private int readBrackets(String args, int idx) {
               for(int i=idx+1,nxtpos=0;i<args.length();i++)
               {
                   nxtpos=calculateNextPosition(i);
                   if(Character.isUpperCase(args.charAt(i)) && Character.isUpperCase(args.charAt(indexLen-(indexLen-nxtpos))))
                   {
                       temp=String.valueOf(args.charAt(i));
                       addentry(1);
                   }
                   else if(Character.isUpperCase(args.charAt(i)) && args.charAt(indexLen-(indexLen-nxtpos))=='[')
                   {
                       temp=String.valueOf(args.charAt(i));
                       addentry(1);
                       addToTempHash();
                       tempIndex++;
                       boxOpen++;
                       //suffix=1;
                       i=readBrackets(args, indexLen-(indexLen-nxtpos));
                   }
                   else if(Character.isUpperCase(args.charAt(i))&& args.charAt(indexLen-(indexLen-nxtpos))=='(')
                   {
                       temp=String.valueOf(args.charAt(i));
                       addentry(1);
                       addToTempHash();
                       tempIndex++;
                       roundOpen++;
                       //suffix=1;
                       i=readBrackets(args, indexLen-(indexLen-nxtpos));
                   }
                   else if(Character.isUpperCase(args.charAt(i))&& args.charAt(indexLen-(indexLen-nxtpos))==')')
                   {
                         temp=String.valueOf(args.charAt(i));
                         addentry(1);
                         i=readLower(args, i);
                         i=i-1;
                  }
                   else if(Character.isUpperCase(args.charAt(i)) && args.charAt(indexLen-(indexLen-nxtpos))==']')
                   {
                         temp=String.valueOf(args.charAt(i));
                         addentry(1);
                         i=readLower(args, i);
                         i=i-1;
                   }
                   else if(args.charAt(i)=='(')
                   {
                       roundOpen++;
                       if(!brentry.isEmpty())
                       {
                           addToTempHash();
                           tempIndex++;
                       }
                       continue;
                   }
                   else if(args.charAt(i)=='[')
                   {
                       boxOpen++;
                       if(!brentry.isEmpty())
                       {
                           addToTempHash();
                           tempIndex++;
                       }
                       continue;
                   }
                   else if(Character.isUpperCase(args.charAt(i)))
                   {
                       temp=String.valueOf(args.charAt(i));
                       i=readLower(args, i);
                       i=i-1;
                   }
                   newId=i;
               }
               return newId;
           }
           //This function is used for adding elements in the respective hashmap considering whether any box brackets or round brackets
           //are open if not then add the elements to the reactpro hashmap
           private void addentry(int value) {
                    if (boxOpen > 0)
                   {
                       keyExists = brentry.containsKey(temp);
                       if (roundOpen > 0)
                       {
                           if (keyExists == false)
                               brentry.put(temp, new Integer(value));
                           else
                               updateKeyValue(temp, value, brentry);
                       }
                       else
                       {
                           if (keyExists == false)
                               brentry.put(temp, new Integer(value));
                           else
                               updateKeyValue(temp, value, brentry);
                       }
                   }
                   else if (roundOpen > 0)
                   {
                       keyExists = brentry.containsKey(temp);
                       if (keyExists == false)
                           brentry.put(temp, new Integer(value));
                       else
                           updateKeyValue(temp, value, brentry);
                   }
                   else
                   {
                       keyExists = reactpro[hmRowpos][hmColpos].containsKey(temp);
                       if (keyExists == false)
                           reactpro[hmRowpos][hmColpos].put(temp, new Integer(value));
                       else
                           updateKeyValue(temp, value, reactpro[hmRowpos][hmColpos]);
                   }
           }

           //This function are called when the Box or Round brackets opens we are adding it to the templist hashtable
           //when anyother round or box bracket gets opened
           private void addToTempHash() {
              Enumeration keys=brentry.keys();
              while(keys.hasMoreElements())
              {
                    Object retrievedKey=keys.nextElement();
                     tempList[tempIndex].put(retrievedKey,brentry.get(retrievedKey));
              }
              brentry.clear();
           }
         //For calculating the no of digits after the element.
           private int IsDigit(String args, int idx) {
               String variable = "";
               int newid2 = 0;
               for (int k = idx; k < fullLen; k++)
               {
                  if (Character.isDigit(args.charAt(k)))
                  {
                     variable += String.valueOf(args.charAt(k));
                     newid2 = k;
                  }
                  else
                  {
                      newid2 = k - 1;
                      break;
                  }
                }
                newId = newid2;
                if (variable.equals("") || variable.equals("0"))
                   digitValue = 1;
                else
                  digitValue=Integer.parseInt(variable);
              return newId;
           }
           //For updating the key value stored in the hashtable with that of the value specified after the round or box bracket
           protected void updateentry(Hashtable h, int value) {
              Enumeration keys=h.keys();
              while(keys.hasMoreElements())
              {
                    Object retrievedKey=keys.nextElement();
                     h.put(retrievedKey,(Object)String.valueOf(Integer.parseInt(String.valueOf(h.get(retrievedKey))) * value));
              }
           }
           //This function is called when any box or round brackets gets closed we are updating the brentry hashtable
           //with that of the templist hashtable also checking before adding whether any key exists or not.If exists we are updating the key value
           // with that of brentry hashtable and templist hashtable. And also finally adding it to the final hashtable.
            public void matchElementToUpdate(Hashtable a, Hashtable b) {
                //If a hashmap is empty and the b is not empty then directly copy all the elements from hashmap b to hashmap a
                yesno=a.isEmpty() && !b.isEmpty()?true:false;
                if(yesno==true)
                {
                     Enumeration keys=b.keys();
                     while(keys.hasMoreElements())
                     {
                            Object retrievedKey=keys.nextElement();
                            a.put(retrievedKey, b.get(retrievedKey));
                     }
                }
                else
                {
                     Enumeration keys1=a.keys();
                     while(keys1.hasMoreElements())
                     {
                            Object retrievedKey1=keys1.nextElement();
                            Enumeration keys2=b.keys();
                            while(keys2.hasMoreElements())
                            {
                                   Object retrievedKey2=keys2.nextElement();
                                   if(a.containsKey(retrievedKey2))
                                   {
                                         if(retrievedKey1.equals(retrievedKey2))
                                         {
                                                int result=Integer.parseInt(String.valueOf(a.get(retrievedKey1)))+ Integer.parseInt(String.valueOf(b.get(retrievedKey2)));
                                                       a.put(retrievedKey1,(Object)String.valueOf(result));
                                                       b.remove(retrievedKey2);
                                         }
                                   }
                                   else
                                   {
                                         a.put(retrievedKey2, b.get(retrievedKey2));
                                         b.remove(retrievedKey2);
                                   }
                            }
                     }
                }
                b.clear();
            }
            private void addToReactPro() {
               Enumeration keys=brentry.keys();
               while(keys.hasMoreElements())
               {
                     Object retrievedKey=keys.nextElement();
                     keyExists=reactpro[hmRowpos][hmColpos].containsKey(retrievedKey);
                     if(keyExists==false)
                            reactpro[hmRowpos][hmColpos].put(retrievedKey, brentry.get(retrievedKey));
                     else
                      {
                            int value=Integer.parseInt(String.valueOf(brentry.get(retrievedKey)));
                            updateKeyValue(String.valueOf(retrievedKey),value,reactpro[hmRowpos][hmColpos]);
                     }
               }
               brentry.clear();
            }
             private void updateKeyValue(String key, int newVal, Hashtable h)
             {
                    Enumeration keys=h.keys();
                    while(keys.hasMoreElements())
                    {
                           Object retrievedKey=keys.nextElement();
                           if(retrievedKey.equals(key))
                           {
                                 if(suffix!=0)
                                 {
                                        h.put(retrievedKey,String.valueOf(Integer.parseInt(String.valueOf(h.get(retrievedKey)))* newVal));
                                        suffix=0;
                                 }
                                 else
                                        h.put(retrievedKey,String.valueOf(Integer.parseInt(String.valueOf(h.get(retrievedKey)))+newVal));
                                 break;
                          }
                    }
             }              //This function will return the atomic weight of that particular element which is stored in the hm hashmap
           //which is acting as a database in our case.
           private double getMolWeight(String key)
           {
              double value=0;
              Enumeration keys=hm.keys();
              while(keys.hasMoreElements())
              {
                    Object retrievedKey=keys.nextElement();
                    if(retrievedKey.equals(key))
                    {
                           value=Double.parseDouble(String.valueOf(hm.get(retrievedKey)));
                           break;
                    }
              }
              return value;
           }
           //For calculating the molecular weight of the expression and for storing the molecular weight as per the compounds
           //in the mol_weight variable at a particular row and at a particular's column
           protected void calculateMolWeight(int rindex,int cindex)
           {
              finaloutput=0;
               Enumeration keys=reactpro[rindex][cindex].keys();
               while(keys.hasMoreElements())
               {
                    Object retrievedKey=keys.nextElement();
                    output=getMolWeight(String.valueOf(retrievedKey));
                    finaloutput+=output * Integer.parseInt(String.valueOf(reactpro[rindex][cindex].get(retrievedKey)));
               }
                    System.out.println(finaloutput);
           }
             public static void main(String args[])
             {
                    ElementCalculation obj=new ElementCalculation();
                    obj.setInitialValues();
                    obj.accept();
             }
}

 

Output

Enter your expression  H2SO4
98.07839999999999

 

The code you've provided is a detailed implementation of a chemical formula parser in Java. It involves parsing a string representation of a chemical formula, analyzing elements, their quantities, and nested structures (such as those indicated by brackets). Here’s an overview of the key functions:

  1. initializeDefaultreactPro() & initializeReactPro():
    • These methods initialize a two-dimensional array of Hashtables called reactpro. Each Hashtable will store chemical elements as keys and their corresponding quantities as values.
  2. contains(String args):
    • This method checks if the input string args contains any brackets, which indicates nested groups in the chemical formula.
  3. accept():
    • The main method to handle user input. It initializes parsing by calling other methods to analyze the chemical formula.
  4. getNoOfBrackets(String args):
    • Counts the number of brackets in the formula, initializing tempList to store intermediate results.
  5. calculateLength(String args) & calculateNextPosition(int org):
    • These methods help in determining the length of the input string and the next position to analyze within the string.
  6. readAtom(String args):
    • This method analyzes the string to identify chemical elements and their quantities. It handles upper and lower case letters, digits, and nested structures within brackets.
  7. readLower(String args, int idx):
    • Handles elements that are represented by two letters, like "Cl" in "NaCl", and processes digits following these elements.
  8. readBrackets(String args, int idx):
    • Processes expressions within brackets, allowing the program to handle nested chemical groups.
  9. addentry(int value):
    • Adds an element and its quantity to the current Hashtable, considering if it’s within any nested structure.
  10. addToTempHash():
    • Transfers entries from brentry to tempList when a new nested structure begins.
  11. IsDigit(String args, int idx):
    • Extracts the numerical value following an element, which represents the quantity of that element.
  12. updateentry(Hashtable h, int value):
    • Updates the quantities of elements in a Hashtable by multiplying them when a bracket is closed.
  13. matchElementToUpdate(Hashtable a, Hashtable b):
    • Merges two Hashtables by summing up quantities of identical elements.
  14. addToReactPro():
    • Adds the elements from brentry to the final reactpro Hashtable once all nested structures are resolved.
  15. updateKeyValue(String key, int newVal, Hashtable h):
    • Updates the quantity of an existing element in a Hashtable by adding the new quantity.

Observations:

  • Data Structures: The program uses arrays of Hashtables to store and manage elements and their quantities. It keeps track of nested groups through the tempList and brentry.
  • Complexity: The program handles complex chemical formulas, including those with nested groups of elements and different quantities.

Potential Enhancements:

  1. Error Handling: Implementing better exception handling, especially for cases where the input string might not follow the expected format.
  2. User Input: Instead of hardcoding args="H2SO4", you could take user input dynamically using a scanner or another input method.
  3. Code Structure: Refactoring the code into smaller methods could improve readability and maintainability.

If you need further explanation on any part of this code or additional help with Java programming, feel free to ask!

 




Molecular weight of chemistry in program language
Molecular weight of chemistry in program language





Post a Comment

0 Comments