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...
# Write a function called `get_state_data` that allows you to specify a state, # then saves...
# Write a function called `get_state_data` that allows you to specify a state, # then saves a .csv file (`STATE_data.csv`) with observations from that state # This includes data about the state, as well as the counties in the state # You should use the full any.drinking dataset in this function (not just 2012) # Demonstrate that you function works by passing "Utah" to the function state_Utah <- get_state_data(Utah) ############################ Binge drinking Dataset ############################ # In this section, you will...
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...
Please solve in C++ only class is not templated You need to write a class called...
Please solve in C++ only class is not templated You need to write a class called LinkedList that implements the following List operations: public void add(int index, Object item); // adds an item to the list at the given index, that index may be at start, end or after or before the // specific element 2.public void remove(int index); // removes the item from the list that has the given index 3.public void remove(Object item); // finds the item from...
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...
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...
Requirements:   You are to write a class called Point – this will represent a geometric point...
Requirements:   You are to write a class called Point – this will represent a geometric point in a Cartesian plane (but x and y should be ints).   Point should have the following: Data:   that hold the x-value and the y-value. They should be ints and must be private. Constructors: A default constructor that will set the values to (2,-7) A parameterized constructor that will receive 2 ints (x then y) and set the data to what is received. A copy...
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)...
Requirements:   You are to write a class called Point – this will represent a geometric point...
Requirements:   You are to write a class called Point – this will represent a geometric point in a Cartesian plane (but x and y should be ints).   Point should have the following: Data:   that hold the x-value and the y-value. They should be ints and must be private. Constructors: A default constructor that will set the values to (2,-7) A parameterized constructor that will receive 2 ints (x then y) and set the data to what is received. A copy...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT