Question

In: Computer Science

Write a class called CompoundManager that allows you to save all compounds in memory to a...

Write a class called CompoundManager that allows you to save all compounds in memory to a text or binary file and then read a list of compounds from a text or binary file and append these to those in memory, those that don’t already exist. In other words, if Ammonia is in memory and the system reads a file that contains Ammonia, then it is ignored, and it moves on to the next compound in the file. Please write the code so that it works with this existing code for the class ChemicalComp (that allows the you to create compounds. The elements can be specified in any order and this order should be preserved. For example, if the scientist supplies: “Ammonia”, “N”, “1”, “H”, “3”, then the formula is: NH3. Note that if the number of atoms is 1, then the 1 should not be used when the formula is requested.) below:

package abi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
//import java.util.Scanner;
public class ChemicalComp {
   public static void main(String[] args) throws IOException{
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       Map data = new HashMap();
       while(true){
           String readinput=br.readLine();
           if(readinput.equals(""))
               break;
                  String input = readinput.replaceAll("\"", "");
                  String array[]=input.split(", ");
                  String compound=array[0];
                  String formula="";
      
                  for(int i=1;i                       if(!array[i].equals("1")){
                          formula+=array[i];
                      }
                  }
                  data.put(compound, formula);
       }
       if(!data.isEmpty()) {
           @SuppressWarnings("rawtypes")
       Iterator it = data.entrySet().iterator();
           while(it.hasNext()) {
               @SuppressWarnings("rawtypes")
       Map.Entry obj = (Entry) it.next();
               System.out.println(obj.getKey()+":"+obj.getValue());
           }
       }

       }

  
}

How the code works above:

"Ammonia", "N", "1", "H", "3"
If the Enter key is pressed without any input is pressed then the input getting process is terminated.

The compound and formula is stored using hashmap keyvalue pairs.

Please use the following elements as a test for the CompoundManager class code:

Water: H2O

Ammonia: NH3

Abamectin: C48H72O14

Ethenol: CH2CHOH

Sulfine: H2CSO

Please and Thank you I rate if the code is written and works correctly as stated. (If absolutely needed code above can be modified if that helps with the CompoundManager class if so please state modifications to ChemcialComp class. Both codes must still work properly however.)

Solutions

Expert Solution

Please find the answer below.
Please do comments in case of any issue. Also, don't forget to rate the question. Thank You.

ChemicalComp.java

package c8;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Map.Entry;
//import java.util.Scanner;
public class ChemicalComp {

   public static void storeDataToFile(Map data, String string){
       try {
           PrintWriter outputFile = new PrintWriter(string);
           @SuppressWarnings("rawtypes")
           Iterator it = data.entrySet().iterator();
           while(it.hasNext()) {
               @SuppressWarnings("rawtypes")
               Map.Entry obj = (Entry) it.next();
               outputFile.println(obj.getKey()+":"+obj.getValue());
           }
           outputFile.close();
           System.out.println("Data exported to file successfully!!!");
       }catch(Exception e){
           System.out.println("Error while exporting data...");
       }
   }


   public static void getDataFromFile(Map data, String string){
       File file = new File(string); //reading data from this file
       Scanner reader;
       String line="";
       try {
           reader = new Scanner(file);
           String datas[];
           while(reader.hasNextLine()){
               line = reader.nextLine();
               datas = line.split(":");
               data.put(datas[0], datas[1]);
           }
           System.out.println(data.size()+" Data loaded from file successfully!!!");
       } catch (FileNotFoundException e) {
           System.out.println("file not found....");
       }

   }

   public static void main(String[] args) throws IOException{
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       Map data = new HashMap();
       getDataFromFile(data,"chemicalElem.txt");
       System.out.println("Enter elements below or empty to stop");
       while(true){
           String readinput=br.readLine();
           if(readinput.equals(""))
               break;
           String input = readinput.replaceAll("\"", "");
           String array[]=input.split(",");
           String compound=array[0];
           String formula="";

           for(int i=1;i<array.length;i++)
               if(!array[i].equals("1")){
                   formula+=array[i];
               }
           if(!data.containsKey(compound)){
               data.put(compound, formula);
           }else{
               System.out.println("Error !!! "+compound+" already exists in Map....");
           }
       }
       if(!data.isEmpty()) {
           @SuppressWarnings("rawtypes")
           Iterator it = data.entrySet().iterator();
           while(it.hasNext()) {
               @SuppressWarnings("rawtypes")
               Map.Entry obj = (Entry) it.next();
               System.out.println(obj.getKey()+":"+obj.getValue());
           }
       }


       storeDataToFile(data,"chemicalElem.txt");

   }
}

First time run:

second run

third run

no entry


Related Solutions

Write a OOP class called BookList that uses a Book class and allows multiple books to...
Write a OOP class called BookList that uses a Book class and allows multiple books to be entered into a BookList object. Include normally useful methods and boolean addBook(Book b), Book searchBook(String title, String author). addBook returns true if b is successfully added to the list. searchBook returns a book matching either the title or author from the current list. You do not need to write Book (assume there are suitable constructors and methods) or any test code (main). You...
1- Write a class called MedicalStaff that is a Person (the class that you wrote in...
1- Write a class called MedicalStaff that is a Person (the class that you wrote in last lab). A MedicalStaff has specialty (i.e. Orthopedic, cardiology, etc.). 2- Then write two classes: Doctor class has office visit fee. Nurse class has title (i.e. RN, NP, etc.) Both classes inherit from MedicalStaff. Be sure these are all complete classes, including toString method. 3- Write a tester to test these classes and their methods, by creating an array or ArrayList of Person and...
Problem Description: SavingsAccount Develop a C++ class declaration called SavingsAccount class that allows user to input...
Problem Description: SavingsAccount Develop a C++ class declaration called SavingsAccount class that allows user to input initial values of dollars and cents and then asks for deposits and withdrawals. The class should include the following information: Operations (Member Functions) 1. Default constructor that sets both dollars and cents to 0. 2. The constructor has 2 parameters that set dollars and cents to the indicated values. 3. Open account (with an initial deposit). This is called to put initial values in...
Task You will write a class called Grid, and test it with a couple of programs....
Task You will write a class called Grid, and test it with a couple of programs. A Grid object will be made up of a grid of positions, numbered with rows and columns. Row and column numbering start at 0, at the top left corner of the grid. A grid object also has a "mover", which can move around to different locations on the grid. Obstacles (which block the mover) and other objects (that can be placed or picked up)...
Write a GUI-based program that allows the user to open, edit, and save text files. The...
Write a GUI-based program that allows the user to open, edit, and save text files. The GUI should include a labeled entry field for the filename and multi-line text widget for the text of the file. The user should be able to scroll through the text by manipulating a vertical scrollbar. Include command buttons labeled Open, Save, and New that allow the user to open, save and create new files. The New command should then clear the text widget and...
Write a Java class called CityDistances in a class file called CityDistances.java.    1. Your methods...
Write a Java class called CityDistances in a class file called CityDistances.java.    1. Your methods will make use of two text files. a. The first text file contains the names of cities. However, the first line of the file is a number specifying how many city names are contained within the file. For example, 5 Dallas Houston Austin Nacogdoches El Paso b. The second text file contains the distances between the cities in the file described above. This file...
We have created an ArrayList of Person class. write a method called push that pushes all...
We have created an ArrayList of Person class. write a method called push that pushes all the people with the even length last name to the end of the ArrayList Content of the ArrayList before push [alex Bus, Mary Phillips, Nik Lambard, Rose Rodd, Esa khan, Jose Martinex, Nik Patte] content of the ArrayList after the push method [alex Bus, Nik Lambard, Nik Patte, Mary Phillips, Rose Rodd, Esa khan, Jose Martinex] import java.util.*; class Person { private String name;...
Write a class in Java called 'RandDate' containing a method called 'getRandomDate()' that can be called...
Write a class in Java called 'RandDate' containing a method called 'getRandomDate()' that can be called without instantiating the class and returns a random Date between Jan 1, 2000 and Dec 31, 2010.
Java - Write an abstract class called Shape with a string data field called colour. Write...
Java - Write an abstract class called Shape with a string data field called colour. Write a getter and setter for colour. Write a constructor that takes colour as the only argument. Write an abstract method called getArea()
Write a class file called lastname_digits.java. In it, write a method to compute and return the...
Write a class file called lastname_digits.java. In it, write a method to compute and return the total instances where the sum of digits of the array equals to the target. Write a demo file called lastname_digits_demo.java. Create an array of random 10 integers between 301 and 999. Also create an integer variable called target that is equal to a value between 5 and 10. Print the answer within this file. Example: If five of the 20 integers are equal to...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT