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...
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...
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()
FOR C++ A friend wants you to start writing a video game. Write a class called...
FOR C++ A friend wants you to start writing a video game. Write a class called “Player” that includes the location of the player, her/his current score, and the ancestry of the player (e.g. “Elf”, “Goblin”, “Giant”, “Human”). A player will always start at location (0, 0) and have a score of 0. Write accessors/modifiers (or “setters/getters”) for each of those characteristics. Write an “appropriate” constructor for the class (based on what’s described above). Write methods moveNorth(), moveSouth(), moveEast() and...
AskInfoPrintInfo Write a program called AskInfoPrintInfo. It should contain a class called AskInfoPrintInfo that contains the...
AskInfoPrintInfo Write a program called AskInfoPrintInfo. It should contain a class called AskInfoPrintInfo that contains the method main. The program should ask for information from the user and then print it. Look at the examples below and write your program so it produces the same input/output. Examples (the input from the user is in bold face) % java AskInfoPrintInfo enter your name: jon doe enter your address (first line): 23 infinite loop lane enter your address (second line): los angeles,...
Write a class called Animal that contains a static variable called count to keep track of...
Write a class called Animal that contains a static variable called count to keep track of the number of animals created. Your class needs a getter and setter to manage this resource. Create another variable called myCount that is assigned to each animal for each animal to keep track of its own given number. Write a getter and setter to manage the static variable count so that it can be accessed as a class resource
Java Write a class called Triangle that can be used to represent a triangle. Write a...
Java Write a class called Triangle that can be used to represent a triangle. Write a class called Describe that will interface with the Triangle class The Server • A Triangle will have 3 sides. It will be able to keep track of the number of Triangle objects created. It will also hold the total of the perimeters of all the Triangle objects created. • It will allow a client to create a Triangle, passing in integer values for the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT