Question

In: Computer Science

In JAVA : There are two text files with the following information stored in them: The...

In JAVA :

There are two text files with the following information stored in them:

The instructor.txt file where each line stores the id, name and affiliated department of an instructor separated by a comma The department.txt file where each line stores the name, location and budget of the department separated by a comma

You need to write a Java program that reads these text files and provides user with the following menu:

1. Enter the instructor ID and I will provide you with the name of the instructor, affiliated department and the location of that department.

2. Enter the department name and I will provide you with the location, budget and names of all instructors that work for the department.

3. Insert a record about a new instructor.

4. Exit

The above menu should continue to be displayed in a loop until the user selects option 4.

When the user selects option 1 above, the following should be displayed:

Enter the instructor ID:

If the user enters an instructor id that is not present in the text file, display "The ID doesnot appear in the database.", otherwise, display the name of the instructor, affiliated department and the location of that department.

When the user selects option 2 above, the following should be displayed:

Enter the department name:

If the user enters a name that is not present in the text file, display "The department name doesnot appear in the database.", otherwise, display the location, budget and names of all instructors that work for the department.

If the user selects option 3 above, display the following:

Enter the instructor id:

Enter the instructor name:

Enter the affiliated department name:

Once the user enters the above information, store the information in the instructor file only if the following two conditions are met: 1. The department already exists in the department file. If not, display "The department doesnot exist and hence the instructor record cannot be added to the database". 2. The instructor id should not already be present in the file. If so, display "Instructor id already exists in the file"

The program should work for any number of rows in the two text files.

The code should use good programming practices with sensible variable names, proper indentation and comments where needed.

Solutions

Expert Solution

Here is your program: 3 classes, one driver, one is department and one is instructor class. (screenshot and text code included)

Code Screenshot

Code ((Text))

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class DatabaseManager {

    public static void main(String[] args) throws Exception {
        //Store instructor from file.
        List<Instructor> instructorList = new ArrayList<>();
        //Store departments from file.
        List<Department> departmentList = new ArrayList<>();

        /* Read and store department from department.txt */
        try {
            //file input stream object to get stream of file.
            FileInputStream stream = new FileInputStream("department.txt");
            //scanner to read line by line.
            Scanner scanner = new Scanner(stream);
            //read line by line until there is line.
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                //If line is empty, read next line.
                if (line.trim().isEmpty())
                    continue;
                //Split all the data with comma.
                String[] data = line.split(",");
                //Create new department and put it into list.
                Department department = new Department(
                        data[0], data[1], Double.valueOf(data[2]));
                departmentList.add(department);
            }
            stream.close();
        } catch (FileNotFoundException fe) {
            System.out.println("Unable to read department.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }

        /* Start reading instructors from file and insert in list */
        try {
            FileInputStream stream = new FileInputStream("instructor.txt");
            Scanner scanner = new Scanner(stream);
            while (scanner.hasNextLine()) {
                String[] data = scanner.nextLine().split(",");
                Instructor instructor = new Instructor(
                        Integer.parseInt(data[0]), data[1], data[2]);
                instructorList.add(instructor);
            }
            stream.close();
        } catch (FileNotFoundException fe) {
            System.out.println("Unable to read instructor.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
        /* buffered writer use to write new instructor to the instructor list. */
        BufferedWriter writer;

        /* Create output stream for instructor file. */
        try {
            FileOutputStream stream = new FileOutputStream("instructor.txt", true);
            writer = new BufferedWriter(new OutputStreamWriter(stream));
        } catch (FileNotFoundException fe) {
            System.out.println("Unable to open instructor.txt for writing.");
            writer = null;
            System.exit(0);
        }
        //Scanner object to read user input.
        Scanner input = new Scanner(System.in);

        //Flag for exiting loop if user select to exit.
        boolean exitProgram = false;
        //Loop until user choice to exit. or something happens wrong.
        while (!exitProgram) {
            //Print the menu
            System.out.println("1. Enter the instructor ID and I will provide " +
                    "you with the name of the instructor, " +
                    "affiliated department and the location of that department.");

            System.out.println("2. Enter the department name and I will provide you " +
                    "with the location, budget and names of all instructors " +
                    "that work for the department.");

            System.out.println("3. Insert a record about a new instructor.");

            System.out.println("4. Exit");

            System.out.println("Enter choice[1-4]: ");

            //Read the user choice.
            String choice = input.nextLine();

            switch (choice) {
                //User choose to display instructor.
                case "1":
                    System.out.print("Enter instructor ID: ");
                    //Read instructor id
                    int id = input.nextInt();
                    //Skip the new line (it will come with integer input)
                    input.nextLine();
                    //Loop through instructor list and find.
                    Instructor instructor = null;
                    for (Instructor ins : instructorList) {
                        if (ins.id == id) {
                            //If instructor found, get it reference and break the loop.
                            instructor = ins;
                            break;
                        }
                    }

                    //If instructor is null, it means instructor not found.
                    if (instructor == null) {
                        System.out.println("The ID doesnot appear in the database.");
                    } else {
                        //Now find the instructor department.
                        for (Department department : departmentList) {
                            //If found, display the information and break the loop.
                            if (instructor.department.equals(department.name)) {
                                System.out.println("Instructor Name: " + instructor.name);
                                System.out.println("Department Name: " + instructor.department);
                                System.out.println("Department Location: " + department.location);
                                break;
                            }
                        }
                    }
                    break;

                case "2":
                    //User choose to display department.
                    System.out.print("Enter the department name:");
                    //Read the department name.
                    String dept = input.nextLine();
                    Department department = null;
                    //Search for department.
                    for (Department d : departmentList) {
                        if (d.name.equals(dept)) {
                            department = d;
                            break;
                        }
                    }
                    //if found display the information else display error.
                    if (department == null) {
                        System.out.println("The department name doesnot appear in the database.");
                    } else {
                        System.out.println("Department Location: " + department.location);
                        System.out.println("Department Budget: " + department.budget);
                        System.out.println("Instructor List: ");

                        for (Instructor i : instructorList) {
                            if (i.department.equals(department.name)) {
                                System.out.println(i.name);
                            }
                        }
                    }
                    break;

                case "3":
                    //User choose to enter new instructor.
                    //Read the detail of instructor.
                    System.out.print("Enter the instructor id:");
                    int insId = input.nextInt();
                    input.nextLine();
                    System.out.print("Enter the instructor name:");
                    String insName = input.nextLine();
                    System.out.print("Enter the affiliated department name:");
                    String insDept = input.nextLine();

                    //Flag for dept, and id
                    boolean isDeptExist = false;
                    boolean isInsIdExist = false;
                    //Check for department existence.
                    for (Department d : departmentList) {
                        if (d.name.equals(insDept)) {
                            isDeptExist = true;
                            break;
                        }
                    }

                    //Check for instructor id existence.
                    for (Instructor i : instructorList) {
                        if (i.id == insId) {
                            isInsIdExist = true;
                            break;
                        }
                    }
                    //If id found in list, display error.
                    if (isInsIdExist) {
                        System.out.println("Instructor id already exists in the file");

                    }
                    //else if department not found, display error.
                    else if (!isDeptExist) {

                        System.out.println("The department doesnot exist and hence the " +
                                "instructor record cannot be added to the database");
                    }
                    //Else enter the instructor, and append in the file too.
                    else {
                        Instructor instructor1 = new Instructor(insId, insName, insDept);
                        instructorList.add(instructor1);
                        writer.write(String.format("%d,%s,%s\n", insId, insName, insDept));
                    }
                    break;

                case "4":
                    //Exit the program.
                    exitProgram = true;
                    break;
            }

        }
    }
}

//Instructor class
class Instructor {
    int id;
    String name;
    String department;

    public Instructor(int id, String name, String department) {
        this.id = id;
        this.name = name;
        this.department = department;
    }


}

//Department class
class Department {
    String name;
    String location;
    double budget;

    public Department(String name, String location, double budget) {
        this.name = name;
        this.location = location;
        this.budget = budget;
    }
}




Output


Related Solutions

I need this in java on textpad. There are two files, both have instructions in them...
I need this in java on textpad. There are two files, both have instructions in them on what to add in the code. They are posted below. public class MyArrayForDouble { double[] nums; int numElements; public MyArrayForDouble() { // Constructor. automatically called when creating an instance numElements = 0; nums = new double[5]; } public MyArrayForDouble(int capacity) { // Constructor. automatically called when creating an instance numElements = 0; nums = new double[capacity]; } public MyArrayForDouble(double[] nums1) { nums =...
Please do the following in JAVA. Deposit and Withdrawal Files Use Notepad or another text editor...
Please do the following in JAVA. Deposit and Withdrawal Files Use Notepad or another text editor to create a text file named Deposits.txt. The file should contain the following numbers, one per line: 100.00 124.00 78.92 37.55 Next, create a text file named Withdrawals.txt. The file should contain the following numbers, one per line: 29.88 110.00 27.52 50.00 12.90 The numbers in the Deposits.txt file are the amounts of deposits that were made to a savings account during the month,...
Java 20 most frequent words in a text file. Words are supposed to be stored in...
Java 20 most frequent words in a text file. Words are supposed to be stored in array that counts eah word. Write a program that will read an article, parse each line into words, and keep track of how many times each word occurred. Run this program for each of the two articles and print out the 20 most frequently appearing words in each article. You may think you need to use a StringTokenizer, but it turns out that is...
C# Simple Text File Merging Application - The idea is to merge two text files located...
C# Simple Text File Merging Application - The idea is to merge two text files located in the same folder to create a new txt file (also in the same folder). I have the idea, and I can merge the two txt files together, however I would like to have an empty line between the two files. How would I implement this in the code below? if (File.Exists(fileNameWithPath1)) { try { string[] file1 = File.ReadAllLines(fileNameWithPath1); string[] file2 = File.ReadAllLines(fileNameWithPath2); //dump...
We will do some basic data analysis on information stored in external files. You will find...
We will do some basic data analysis on information stored in external files. You will find the following data files in the Source Code -> Chapter 7 folder you should have downloaded already downloaded/unzipped in Lesson 3. If you need that link again: Pyton4E_Source_Code.zip GirNames.txt contains a list of the 200 most popular names given to girls born in US from year 2000 thru 2009 BoyNames.txt contains a list of the 200 most popular names given to boys born in...
Files I need to be edited: I wrote these files and I put them in a...
Files I need to be edited: I wrote these files and I put them in a folder labeled Project 7. I am using this as a study tool for a personal project of mine. //main.cpp #include <iostream> #include "staticarray.h" using namespace std; int main( ) {    StaticArray a;    cout << "Printing empty array -- next line should be blank\n";    a.print();    /*    // Loop to append 100 through 110 to a and check return value    // Should print "Couldn't append 110"...
Write Java program Lab52.java which reads in a line of text from the user. The text...
Write Java program Lab52.java which reads in a line of text from the user. The text should be passed into the method: public static String[] divideText(String input) The "divideText" method returns an array of 2 Strings, one with the even number characters in the original string and one with the odd number characters from the original string. The program should then print out the returned strings.
In Java: (1) Create two files to submit: ItemToBuy.java - Class definition ShoppingCartDriver.java - Contains main()...
In Java: (1) Create two files to submit: ItemToBuy.java - Class definition ShoppingCartDriver.java - Contains main() method Build the ItemToBuy class with the following specifications: Private fields String itemName - Initialized in the nor-arg constructor to "none" int itemPrice - Initialized in default constructor to 0 int itemQuantity - Initialized in default constructor to 0 No-arg Constructor (set the String instance field to "none") Public member methods (mutators & accessors) setName() & getName() setPrice() & getPrice() setQuantity() & getQuantity() toString()...
Write a Java program that will encode plain text into cipher text and decode cipher text...
Write a Java program that will encode plain text into cipher text and decode cipher text into plain text. Create following methods and add them to your class: • a method named encode(String p, int key) that takes a plain text p and encodes it to a cipher text by adding the key value to each alphabet character of plain text p using the ASCII chart. The method should return the encoded String. For example, if p = "attack at...
When using random access files in Java, the programmer is permitted to create files which can...
When using random access files in Java, the programmer is permitted to create files which can be read from and written to random locations. Assume that a file called "integers.dat" contains the following values: 25 8 700 284 63 12 50 Fill in blanks: You are required to write the following Java code statements: (a) create a new stream called, blueray, which allows the program to read from and write to the file, "integers.dat." _____________________ (b) Write a statement which...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT