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 =...
Java Linked Lists I want a simple program that reads two text files that contains an...
Java Linked Lists I want a simple program that reads two text files that contains an integers matrix and store each file into a linked lists matrix so I can later preform operations such as addition and subtraction on the matrices an example of the input text files: sample a 2 6 2 6 2 18 17 11 20 sample b 3 13 5 4 11 20 13 18 20
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...
In JAVA (eclipse).... Extract both files and place them in your program’s folder. You will be...
In JAVA (eclipse).... Extract both files and place them in your program’s folder. You will be using them. In your driver class: • Create an array called “boyNames” and store all names from the BoyNames.txt file • Similarly, create an array called “girlsNames” and store all names from the GirlNames.txt file • Create a text menu that allowing users to: 1. Enter a name and the application must display a message indicating if the name is among the most popular...
File Compare Write a program that opens two text files and reads their contents into two...
File Compare Write a program that opens two text files and reads their contents into two separate queues. The program should then determine whether the files are identical by comparing the characters in the queues. When two nonidentical characters are encountered, the program should display a message indicating that the files are not the same. If both queues contain the same set of characters, a message should be displayed indicating that the files are identical. // Copyright (c) 2013 __Pearson...
a python function that reads two text files and merges in to one Linked List, be...
a python function that reads two text files and merges in to one Linked List, be able to print each Item in the new single Linked List class Node(object): item = -1 next = None def __init__(self, item, next): self.item = item self.next = next ================================ textfile! 979 2744 5409 1364 4948 4994 5089 703 1994 4637 2228 4004 1088 2812 170 5179 2614 238 4523 4849 3592 3258 1951 3440 3977 1247 4076 1824 4759 4855 5430 347 974...
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"...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT