Question

DatabaseFilter Design a DatabaseFilter class that will manage the file 1/O (input/output) of an employee ArrayList object. Fo
parse: returns an object that is compatible with an employee object. This method could V. an or possibly IllegalArgument Exce
vii search: searches for the employee name and returns output to the console screen. public void search (String name) throws
0 0
Add a comment Improve this question Transcribed image text
Answer #1

//================ Main.java ================
//Tester class


import java.io.BufferedReader;
import java.io.File;

import java.io.FileReader;

public class Main
{
   DatabaseFilter filter;
   Main()
   {
       filter = new DatabaseFilter();
      
   }
   public void filterOver40Tester(String location)
   {
       try
       {
           System.out.println("\n**************** Filter Over 40 Tester ***************\n");
           filter.filterOver40(location);
           displayData(location);
           System.out.println("\n**************** END of Test ***************\n");
       }
       catch(Exception e)
       {
           System.out.println("\n------------------ Exception at filterOver40Tester ----------------------\n");
           System.out.println(e.getMessage());
           System.out.println("\n------------------ End Of Exception ----------------------");
       }
   }
  
   public void filterUnder40Tester(String location)
   {
       try
       {
           System.out.println("\n**************** Filter Under 40 Tester ***************\n");
           filter.filterUnder40(location);
           displayData(location);
           System.out.println("\n**************** END of Test ***************\n");
       }
       catch(Exception e)
       {
           System.out.println("\n------------------ Exception at filterUnder40Tester ----------------------\n");
           System.out.println(e.getMessage());
           System.out.println("\n------------------ End Of Exception ----------------------");
       }
   }
  
   public void filterSalaryTester(String location)
   {
       try
       {
           System.out.println("\n**************** Filter Salary Tester ***************\n");
           filter.filterSalary(location);
           displayData(location);
           System.out.println("\n**************** END of Test ***************\n");
       }
       catch(Exception e)
       {
           System.out.println("\n------------------ Exception at filterSalaryTester ----------------------\n");
           System.out.println(e.getMessage());
           System.out.println("\n------------------ End Of Exception ----------------------");
       }
   }
  
   public void filterService(String location)
   {
       try
       {
           System.out.println("\n**************** Filter Service Tester ***************\n");
           filter.filterService(location);
           displayData(location);
           System.out.println("\n**************** END of Test ***************\n");
       }
       catch(Exception e)
       {
           System.out.println("\n------------------ Exception at filterService ----------------------\n");
           System.out.println(e.getMessage());
           System.out.println("\n------------------ End Of Exception ----------------------");
       }
   }
  
   public void readTester(String location)
   {
       try
       {
           System.out.println("\n**************** Reader Tester ***************\n");
           filter.read(location);
           filter.printEmployees();
           System.out.println("\n**************** END of Test ***************\n");
       }
       catch(Exception e)
       {
           System.out.println("\n------------------ Exception at readTester ----------------------\n");
           System.out.println(e.getMessage());
           System.out.println("\n------------------ End Of Exception ----------------------");
       }
   }
  
   public void searchTester(String name)
   {
       try
       {
           System.out.println("\n**************** Search Tester ***************\n");
           filter.search(name);
          
           System.out.println("\n**************** END of Test ***************\n");
       }
       catch(Exception e)
       {
           System.out.println("\n------------------ Exception at searchTester ----------------------\n");
           System.out.println(e.getMessage());
           System.out.println("\n------------------ End Of Exception ----------------------");
       }
   }
  
   public void writeTester(String location)
   {
       try
       {
           System.out.println("\n**************** Writer Tester ***************\n");
           filter.write(location);
           displayData(location);
           System.out.println("\n**************** END of Test ***************\n");
       }
       catch(Exception e)
       {
           System.out.println("\n------------------ Exception at writeTester ----------------------\n");
           System.out.println(e.getMessage());
           System.out.println("\n------------------ End Of Exception ----------------------");
       }
   }
  
   public void writeCSTester(String location)
   {
       try
       {
           System.out.println("\n**************** WriterCS Tester ***************\n");
           filter.writeCS(location);
           displayData(location);
           System.out.println("\n**************** END of Test ***************\n");
       }
       catch(Exception e)
       {
           System.out.println("\n------------------ Exception at writeCSTester ----------------------\n");
           System.out.println(e.getMessage());
           System.out.println("\n------------------ End Of Exception ----------------------");
       }
   }
  
   public void sortAlphabeticalOrderTester(String location)
   {
       try
       {
           System.out.println("\n**************** Sort Alphabetical Order Tester ***************\n");
           filter.sortAlphabeticalOrder(location);
           displayData(location);
           System.out.println("\n**************** END of Test ***************\n");
       }
       catch(Exception e)
       {
           System.out.println("\n------------------ Exception at sortAlphabeticalOrderTester ----------------------\n");
           System.out.println(e.getMessage());
           System.out.println("\n------------------ End Of Exception ----------------------");
       }
   }
  
   public void displayData(String location)
   {
       File f = new File(location);
       System.out.println("\nDisplaying Data in : "+location+"\n");
       if(f.canRead() == false)
       {
           System.err.println("Unable to perform Read in File: "+location);
           return;
       }
      
       try
       {
           BufferedReader reader = new BufferedReader(new FileReader(f));
           String line = reader.readLine();
           while(line != null)
           {
               try
               {
                   Employee emp = filter.parse(line);
                   System.out.println(emp);
               }
               catch(Exception e)
               {
                  
                   System.err.println("Exception occured while reading Line: "+line);
                   System.out.println("Exception Details: "+e.getMessage());
                  
               }
               line = reader.readLine();
           }
           reader.close();
       }
       catch(Exception e)
       {
          
           System.err.println("Exception Occured while reading the File: "+location);
           System.err.println("Details about exception: "+e.getMessage());
          
       }
   }
   public static void main(String[] args)
   {
      
       //you have to pass absolute path to the functions as locations.
       //or else you will get FileNotFoundException.
       //all the files are in current working directory.
       //so i get current path using absolute path from java.nio.file.Paths
       Main tester = new Main();
      
       tester.readTester("emp.txt");
       tester.filterOver40Tester("filterOver40.txt");
       tester.filterUnder40Tester("filterUnder40.txt");
       tester.filterSalaryTester("filterSalary.txt");
       tester.filterService("filterService.txt");
       tester.writeTester("writedEmps.txt");
       tester.writeCSTester("writeCSEmps.txt");
       tester.sortAlphabeticalOrderTester("sortedEmps.txt");
       tester.searchTester("John Wick");
      

   }

}

//================ Employee.java ================


public class Employee
{
   private String name;
   private int age;
   private String office;
   private double salary;
   private double priority;
   public Employee(String n,int a, String off,double sal,double pri)
   {
       name = n;
       age = a;
       office = off;
       salary = sal;
       priority = pri;
   }
   public String getName() {
       return name;
   }
   public int getAge() {
       return age;
   }
   public String getOffice() {
       return office;
   }
   public double getSalary() {
       return salary;
   }
   public double getPriority() {
       return priority;
   }
   public String toString()
   {
       return name+ "," +age+ "," +office+ "," +salary+ "," +priority+"\n";
   }
}


//================ DatabaseFilter.java ================


import java.util.*;
import java.io.*;
public class DatabaseFilter
{
   private ArrayList<Employee> data;
   public DatabaseFilter()
   {
       data = new ArrayList<Employee>();
   }
  
   public void filterOver40(String location) throws FileNotFoundException
   {
       File f = new File(location);
       if(f.exists() == false)
       {
           throw new FileNotFoundException("File: "+location+" is Not Found");
       }
       if(f.canWrite() == false)
       {
           System.err.println("Unable to perform Write in File: "+location);
           return;
       }
       BufferedWriter writer = null;
       try
       {
           writer = new BufferedWriter(new FileWriter(f));
           for(int i =0;i<data.size();i++)
           {
               Employee emp = data.get(i);
               if(emp.getAge() >=40 )
               {
                   writer.write(""+emp);
               }
           }
           writer.close();
       }
       catch(Exception e)
       {
           System.err.println("Exception Occured while writing into File: "+location);
           System.err.println("Details about exception: "+e.getMessage());
          
       }
      
      
      
   }
  
   public void filterUnder40(String location) throws FileNotFoundException
   {
       File f = new File(location);
       if(f.exists() == false)
       {
           throw new FileNotFoundException("File: "+location+" is Not Found");
       }
       if(f.canWrite() == false)
       {
           System.err.println("Unable to perform Write in File: "+location);
           return;
       }
      
       try
       {
           BufferedWriter writer = new BufferedWriter(new FileWriter(f));
           for(int i =0;i<data.size();i++)
           {
               Employee emp = data.get(i);
               if(emp.getAge() < 40 )
               {
                   writer.write(""+emp);
               }
           }
           writer.close();
       }
       catch(Exception e)
       {
           System.err.println("Exception Occured while writing into File: "+location);
           System.err.println("Details about exception: "+e.getMessage());
       }
      
      
   }
   //method that writes the employee with salary under 55000 into the
   //given location
   public void filterSalary(String location) throws FileNotFoundException
   {
       File f = new File(location);
       if(f.exists() == false)
       {
           throw new FileNotFoundException("File: "+location+" is Not Found");
       }
       if(f.canWrite() == false)
       {
           System.err.println("Unable to perform Write in File: "+location);
           return;
       }
      
       try
       {
           BufferedWriter writer = new BufferedWriter(new FileWriter(f));
           for(int i =0;i<data.size();i++)
           {
               Employee emp = data.get(i);
               if(emp.getSalary() <= 55000 )
               {
                   writer.write(""+emp);
               }
           }
           writer.close();
       }
       catch(Exception e)
       {
           System.err.println("Exception Occured while writing into File: "+location);
           System.err.println("Details about exception: "+e.getMessage());
       }
      
      
   }
   //Method that takes a location and writes the employees
   //whose service is >= 20 years.
   //i have taken priority as the number of years worked(service) of an employee.
   //if the priority of an employee is >=20 then he/she will be written into
   //the file with the given location.
   public void filterService(String location) throws FileNotFoundException
   {
       File f = new File(location);
       if(f.exists() == false)
       {
           throw new FileNotFoundException("File: "+location+" is Not Found");
       }
       if(f.canWrite() == false)
       {
           System.err.println("Unable to perform Write in File: "+location);
           return;
       }
      
       try
       {
           BufferedWriter writer = new BufferedWriter(new FileWriter(f));
           for(int i =0;i<data.size();i++)
           {
               Employee emp = data.get(i);
               if(emp.getPriority() >= 20 )
               {
                   writer.write(""+emp);
               }
           }
           writer.close();
       }
       catch(Exception e)
       {
          
           System.err.println("Exception Occured while writing into File: "+location);
           System.err.println("Details about exception: "+e.getMessage());
          
       }
      
      
   }
   public Employee parse(String line) throws NumberFormatException,IllegalFormatException
   {
       String info[] = line.trim().split(",");
       String name = info[0];
       int age = Integer.parseInt(info[1]);
       String office = info[2];
       double salary = Double.parseDouble(info[3]);
       double priority = Double.parseDouble(info[4]);
       return new Employee(name,age,office,salary,priority);
      
   }
  
   public void read(String location) throws FileNotFoundException
   {
       File f = new File(location);
       if(f.exists() == false)
       {
           throw new FileNotFoundException("File: "+location+" is Not Found");
       }
       if(f.canRead() == false)
       {
           System.err.println("Unable to perform Read in File: "+location);
           return;
       }
      
       try
       {
           BufferedReader reader = new BufferedReader(new FileReader(f));
           String line = reader.readLine();
           while(line != null)
           {
               try
               {
                   Employee emp = parse(line);
                   data.add(emp);
               }
               catch(Exception e)
               {
                  
                   System.err.println("Exception occured while reading Line: "+line);
                   System.out.println("Exception Details: "+e.getMessage());
                  
               }
               line = reader.readLine();
           }
           reader.close();
       }
       catch(Exception e)
       {
          
           System.err.println("Exception Occured while reading the File: "+location);
           System.err.println("Details about exception: "+e.getMessage());
          
       }
   }
   //i think there is a mistake in the function prototype mentioned for search method.
   //throws FileNotFoundException is used but the String location parameter is not given.
   //so assume that it meant to search for name of employee in arraylist of employees.
   //which don't need FileNotFoundException
   //if you think it is not what you required please comment about what you need.
   //i will modify it.
   public void search(String name)
   {
       boolean found = false;
       int ind = -1;
       for(int i =0;i<data.size();i++)
       {
           if(data.get(i).getName().equals(name))
           {
               found = true;
               ind = i;
           }
       }
       if(found)
       {
           System.out.println("\nEmployee with name: "+name+ " is found at index: "+ind);
           System.out.println("Employee Details: ");
           printEmployeeProperty(data.get(ind));
       }
       else
       {
          
           System.out.println("\nEmployee with name: "+name+ " is Not found in Database");
       }
   }
  
   public void sortAlphabeticalOrder(String location) throws FileNotFoundException
   {
       sortEmployees();
       try
       {
           write(location);
       }
       catch(FileNotFoundException e)
       {
           throw new FileNotFoundException("File: "+location+" is Not Found");
       }
      
   }
   public void sortEmployees()
   {
       Collections.sort(data,new EmployeeComparator());
   }
  
   public void write(String location)throws FileNotFoundException
   {
       File f = new File(location);
       if(f.exists() == false)
       {
           throw new FileNotFoundException("File: "+location+" is Not Found");
       }
       if(f.canWrite() == false)
       {
           System.err.println("Unable to perform Write in File: "+location);
           return;
       }
      
       try
       {
           BufferedWriter writer = new BufferedWriter(new FileWriter(f));
           for(int i =0;i<data.size();i++)
           {
               writer.write(""+data.get(i));
           }
           writer.close();
       }
       catch(Exception e)
       {
          
           System.err.println("Exception Occured while writing into File: "+location);
           System.err.println("Details about exception: "+e.getMessage());
          
       }
   }
  
   public void writeCS(String location)throws FileNotFoundException
   {
       File f = new File(location);
       if(f.exists() == false)
       {
           throw new FileNotFoundException("File: "+location+" is Not Found");
       }
       if(f.canWrite() == false)
       {
           System.err.println("Unable to perform Write in File: "+location);
           return;
       }
      
       try
       {
           BufferedWriter writer = new BufferedWriter(new FileWriter(f));
           for(int i =0;i<data.size();i++)
           {
               Employee emp = data.get(i);
               //write comma separated data to file.
               writer.write(emp.getName() + "," + emp.getAge() + "," + emp.getOffice() + "," + emp.getSalary() + "," + emp.getPriority()+"\n");
           }
           writer.close();
       }
       catch(Exception e)
       {
          
           System.err.println("Exception Occured while writing into File: "+location);
           System.err.println("Details about exception: "+e.getMessage());
          
       }
   }
   public void printEmployeeProperty(Employee emp)
   {
       System.out.println("\n\tName: " + emp.getName());
       System.out.println("\tAge: " + emp.getAge());
       System.out.println("\tOffice: " + emp.getOffice());
       System.out.println("\tSalary: " + emp.getSalary());
       System.out.println("\tPriority: " + emp.getPriority());
   }
   public void printEmployees()
   {
       System.out.println("\n----------------- Employees --------------\n");
       for(int i = 0;i<data.size();i++)
       {
           Employee emp = data.get(i);
           printEmployeeProperty(emp);
       }
   }
}

//================ EmployeeComparator.java ================

import java.util.Comparator;
public class EmployeeComparator implements Comparator<Employee>
{
   @Override
   public int compare(Employee one,Employee two)
   {
       //splitting the name to get first name and last name of the employees
       //at 0th index there will be first name
       //at index 1 there will be last name.
       String oneName[] = one.getName().split(" ");
       String twoName[] = two.getName().split(" ");

       //comparing last names for sorting
       int lastNameRes = oneName[1].compareTo(twoName[1]);
       //if last name result is not 0 then return value.
       //last name of first emp is having higher precedence
       if(lastNameRes != 0)
       {
           return lastNameRes;
       }
      
       //comparing first names.
       int firstNameRes = oneName[0].compareTo(twoName[0]);
       //return the result of first names.
       return firstNameRes;
      
   }
}

//====================== Output ====================
**************** Reader Tester ***************


----------------- Employees --------------


   Name: John Smith
   Age: 30
   Office: Development
   Salary: 39000.0
   Priority: 10.0

   Name: Tony Stark
   Age: 44
   Office: Mechanic
   Salary: 56000.0
   Priority: 30.0

   Name: Steve Rogers
   Age: 80
   Office: Technician
   Salary: 32000.0
   Priority: 29.0

   Name: Barry Allen
   Age: 25
   Office: Ground Team
   Salary: 30000.0
   Priority: 15.0

   Name: Sam Watson
   Age: 30
   Office: Ground Team
   Salary: 25000.0
   Priority: 19.0

   Name: John Wick
   Age: 40
   Office: Ground Team
   Salary: 60000.0
   Priority: 40.0

**************** END of Test ***************


**************** Filter Over 40 Tester ***************


Displaying Data in : filterOver40.txt

Tony Stark,44,Mechanic,56000.0,30.0

Steve Rogers,80,Technician,32000.0,29.0

John Wick,40,Ground Team,60000.0,40.0


**************** END of Test ***************


**************** Filter Under 40 Tester ***************


Displaying Data in : filterUnder40.txt

John Smith,30,Development,39000.0,10.0

Barry Allen,25,Ground Team,30000.0,15.0

Sam Watson,30,Ground Team,25000.0,19.0


**************** END of Test ***************


**************** Filter Salary Tester ***************


Displaying Data in : filterSalary.txt

John Smith,30,Development,39000.0,10.0

Steve Rogers,80,Technician,32000.0,29.0

Barry Allen,25,Ground Team,30000.0,15.0

Sam Watson,30,Ground Team,25000.0,19.0


**************** END of Test ***************


**************** Filter Service Tester ***************


Displaying Data in : filterService.txt

Tony Stark,44,Mechanic,56000.0,30.0

Steve Rogers,80,Technician,32000.0,29.0

John Wick,40,Ground Team,60000.0,40.0


**************** END of Test ***************


**************** Writer Tester ***************


Displaying Data in : writedEmps.txt

John Smith,30,Development,39000.0,10.0

Tony Stark,44,Mechanic,56000.0,30.0

Steve Rogers,80,Technician,32000.0,29.0

Barry Allen,25,Ground Team,30000.0,15.0

Sam Watson,30,Ground Team,25000.0,19.0

John Wick,40,Ground Team,60000.0,40.0


**************** END of Test ***************


**************** WriterCS Tester ***************


Displaying Data in : writeCSEmps.txt

John Smith,30,Development,39000.0,10.0

Tony Stark,44,Mechanic,56000.0,30.0

Steve Rogers,80,Technician,32000.0,29.0

Barry Allen,25,Ground Team,30000.0,15.0

Sam Watson,30,Ground Team,25000.0,19.0

John Wick,40,Ground Team,60000.0,40.0


**************** END of Test ***************


**************** Sort Alphabetical Order Tester ***************


Displaying Data in : sortedEmps.txt

Barry Allen,25,Ground Team,30000.0,15.0

Steve Rogers,80,Technician,32000.0,29.0

John Smith,30,Development,39000.0,10.0

Tony Stark,44,Mechanic,56000.0,30.0

Sam Watson,30,Ground Team,25000.0,19.0

John Wick,40,Ground Team,60000.0,40.0


**************** END of Test ***************


**************** Search Tester ***************


Employee with name: John Wick is found at index: 5
Employee Details:

   Name: John Wick
   Age: 40
   Office: Ground Team
   Salary: 60000.0
   Priority: 40.0

**************** END of Test ***************

Add a comment
Know the answer?
Add Answer to:
DatabaseFilter Design a DatabaseFilter class that will manage the file 1/O (input/output) of an employee ArrayList...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • import java.util.Scanner; // TASK #1 Add the file I/O import statement here /** This class reads...

    import java.util.Scanner; // TASK #1 Add the file I/O import statement here /** This class reads numbers from a file, calculates the mean and standard deviation, and writes the results to a file. */ public class StatsDemo { // TASK #1 Add the throws clause public static void main(String[] args) { double sum = 0; // The sum of the numbers int count = 0; // The number of numbers added double mean = 0; // The average of the...

  • I need code in java The Student class: CODE IN JAVA: Student.java file: public class Student...

    I need code in java The Student class: CODE IN JAVA: Student.java file: public class Student {    private String name;    private double gpa;    private int idNumber;    public Student() {        this.name = "";        this.gpa = 0;        this.idNumber = 0;    }    public Student(String name, double gpa, int idNumber) {        this.name = name;        this.gpa = gpa;        this.idNumber = idNumber;    }    public Student(Student s)...

  • In the processLineOfData method, write the code to handle case "H" of the switch statement such...

    In the processLineOfData method, write the code to handle case "H" of the switch statement such that: • An HourlyEmployee object is created using the firstName, lastName, rate, and hours local variables. Notice that rate and hours need to be converted from String to double. You may use parseDouble method of the Double class as follows: Double.parseDouble(rate) Call the parsePaychecks method in this class passing the Hourly Employee object created in the previous step and the checks variable. Call the...

  • Write a unit test to test the following class. Using Java : //Test only the debit...

    Write a unit test to test the following class. Using Java : //Test only the debit method in the BankAccount. : import java.util.*; public class BankAccount { private String customerName; private double balance; private boolean frozen = false; private BankAccount() { } public BankAccount(String Name, double balance) { customerName = Name; this.balance = balance; } public String getCustomerName() { return customerName; } public double getBalance() { return balance; } public void setDebit(double amount) throws Exception { if (frozen) { throw...

  • In the processLineOfData, write the code to handle case "H" of the switch statement such that:...

    In the processLineOfData, write the code to handle case "H" of the switch statement such that: An HourlyEmployee object is created using the firstName, lastName, rate, and hours local variables. Notice that rate and hours need to be converted from String to double. You may use parseDouble method of the Double class as follows:               Double.parseDouble(rate) Call the parsePaychecks method in this class passing the HourlyEmployee object created in the previous step and the checks variable. Call the findDepartment method...

  • In Java(using BlueJ) Purpose Purpose is to practice using file input and output, and array list...

    In Java(using BlueJ) Purpose Purpose is to practice using file input and output, and array list of objects. Also, this lab specification tells you only what to do, you now have more responsibility to design how to do it. Problem description You are given a text file called 'Students.txt' that contains information on many students. Your program reads the file, creating many Student objects, all of which will be stored into an array list of Student objects, in the Students...

  • Below are the Car class and Dealership class that I created In the previous lab import...

    Below are the Car class and Dealership class that I created In the previous lab import java.util.ArrayList; class Car { private String make; private String model; private int year; private double transmission; private int seats; private int maxSpeed; private int wheels; private String type; public Car() { } public Car(String make, String model, int year, double transmission, int seats, int maxSpeed, int wheels, String type) { this.make = make; this.model = model; this.year = year; this.transmission = transmission; this.seats =...

  • C++ Please create the class named BankAccount with the following properties below: // The BankAccount class...

    C++ Please create the class named BankAccount with the following properties below: // The BankAccount class sets up a clients account (name & ID), keeps track of a user's available balance. // It also keeps track of how many transactions (deposits and/or withdrawals) are made. public class BankAccount { Private String name private String id; private double balance; private int numTransactions; // Please define method definitions for Accessors and Mutator functions below Private member variables string getName(); // No set...

  • Complete the implementations of various classes in a Flight Management, We consider a database that stores...

    Complete the implementations of various classes in a Flight Management, We consider a database that stores information about passengers and flights. Each passenger record (e.g., String name, double TicketAmount, int flightID) can be uniquely identified by a String ID (e.g., ”e1”), whereas each flight record (e.g., String airline and String flight for flight name and airline name, respectively ) can be uniquely identified by an integer id. You must implement all methods in the FlightManagementSystem by manipulating the two attributes...

  • Write a Java class called BankAccount (Parts of the code is given below), which has two...

    Write a Java class called BankAccount (Parts of the code is given below), which has two fields name (String) and balance (double), two constructors and five methods getName(), getBalance(), deposit (double amount), withdraw(double amount) and toString(). The first constructor should initialize name to null and balance to 0. The second constructor initializes name and balance to the parameters passed. deposit method deposits the amount to the account causing the current balance to increase, withdraw method withdraws the amount causing the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT