Question

In: Computer Science

Create a program in Java for storing the personal information of students and teachers of a...

Create a program in Java for storing the personal information of students and teachers of a school in a .csv (comma-separated values) file.

The program gets the personal information of individuals from the console and must store it in different rows of the output .csv file.

Input Format

User enters personal information of n students and teachers using the console in the following

format:

n

Position1 Name1 StudentID1 TeacherID1 Phone1

Position2 Name2 StudentID2 TeacherID2 Phone2

Position3 Name3 StudentID3 TeacherID3 Phone3

. . .

Positionn Namen StudentIDn TeacherIDn Phonen


Please note that the first line contains only an integer counting the number of lines

following the first line.

In each of the n given input lines,

  • Position must be one of the following three strings “student”, “teacher”, or “TA”.

  • Name must be a string of two words separated by a single comma only.

  • StudentID and TeacherID must be either “0” or a string of 5 digits. If Position is “teacher”, StudentID is zero, but TeacherID is not zero. If Position is “student”, TeacherID is zero, but StudentID is not zero. If Position is “TA”, neither StudentID nor TeacherID are zero.

  • Phone is a string of 10 digits.


If the user enters information in a way that is not consistent with the mentioned format,

your program must use exception handling techniques to gracefully handle the situation

by printing a message on the screen asking the user to partially/completely re-enter the

information that was previously entered in a wrong format.



Data Structure, Interface and Classes

Your program must have an interface called “CSVPrintable” containing the following three methods:

  • String getName ();

  • int getID ();

  • void csvPrintln ( PrintWriter out);

You need to have two classes called “Student” and “Teacher” implementing CSVPrintable

interface and another class called “TA” extending Student class. Both Student and Teacher classes must have appropriate variables to store Name and ID.

In order to store Phone, Student class must have a phone variable of type long that can store a 10-digit integer; while the Teacher class must have a phone variable of type int to store only the 4-digit postfix of the phone number.

Method getName has to be implemented by both Student and Teacher classes in the same way. Class Student must implement getID in a way that it returns the StudentID and ignores the TeacherID given by the input. Class Teacher must implement getID in a way that it returns the TeacherID and ignores the StudentID given by the input. Class TA must override the Student implementation of getID so that it returns the maximum value of StudentID and TeacherID.

Method csvPrintln has to be implemented by Student and Teacher classes (and overridden by TA class) so that it writes the following string followed by a new line on the output stream out:

getName() + “,” + getID() + “,” + phone



Output .csv File

The program must store the personal information of students, teachers and TAs in a commaseparated values (.csv) file called “out.csv”. You need to construct the output file by repetitively calling the csvPrintln method of every CSVPrintable object instantiated in your program. The output .csv file stores the information of every individual in a separate row; while each column of the file stores different type of information regarding the students and teachers (i.e. Name, ID and phone columns). Please note that you should be able to open the output file of your program using MS-Excel and view it as a table.

Sample Input/Output

Assume that the user enters the following four lines in console:

Teacher Alex,Martinez 0 98765 3053489999

Student Rose,Gonzales 56789 0 9876543210

TA John,Cruz 88888 99999 1234567890

The program must write the following content in the out.csv file.

Alex Martinez,98765,9999

Rose Gonzales,56789,9876543210

John Cruz,99999,1234567890

Solutions

Expert Solution

CSVPrintable.java
-------------------------------------------------------
// import necessary classes 
import java.io.IOException;
import java.io.PrintWriter;

// interface ( defines some abstract methods )
public interface CSVPrintable {

    String getName();
    int getID();
    void csvPrintln(PrintWriter out) throws IOException;

} // END of interface

-----------------------------------------------------------------------------------------------------------------------

file-name :     Student.java
-------------------------------------------
import java.io.PrintWriter;
// Student class implementing CSVPrintable interface
public class Student implements CSVPrintable{
    // members of Student class
    String studentName;
    int studentID;
    long studentMobile;

    // Constructor
    Student(String name , int id, long mobile) {
        studentID = id;
        studentName = name;
        studentMobile = mobile;
    }
    public String getName() {
        return studentName;
    }

    public int getID() {
        return studentID;
    }
    // this method takes PrintWriter as argument and writes the data in String format to the file ( append mode)
    public void csvPrintln(PrintWriter out) {
        String data = getName()+","+getID()+","+studentMobile+"\n";
        out.write(data);
        out.flush();
        out.close();

    }
}

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

file-name;    TA.java
// TA class extends Student class
// TA is the child and Student is parent
// So, TA inherits all the members of Student class 
public class TA extends Student {
    
    // constructor
    TA(String name, int id, long mobile) {
        super(name, id, mobile);
    }

    @Override
    public int getID() {
        return super.getID();
    }
}

-----------------------------------------------------------------------------------------------------------------------------------------

file-name :   Teacher.java
-------------------------------------------
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

// Teacher class implements the interface CSVPrintable
public class Teacher implements CSVPrintable {

    // members 
    String teacherName;
    int teacherID;
    int teacherMobile;

    // constructor
    Teacher(String name, int id, int mobile) {
        teacherName = name;
        teacherID = id;
        teacherMobile = mobile;
    }
    public String getName() {
        return teacherName;
    }
    
    public int getID() {
        return teacherID;
    }

    // this method takes PrintWriter as argument and writes the data in String format to the file ( append mode)
    public void csvPrintln(PrintWriter out) throws IOException {
        String data = getName()+","+getID()+","+teacherMobile+"\n";
        out.write(data);
        out.flush();
        out.close();
    }
}

==========================================================

file-name : Main.java
----------------------------------------------------------
import java.util.*;
import  java.io.*;
import java.lang.Math;

// Main class ( creates objects of all classes and calls thier methods )
public class Main {

    // main( ) method:
    public static void main(String[] args) throws IOException{
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the total number of lines:");
        int n = sc.nextInt();sc.nextLine();
        // while loop to take user input
        while(n > 0) {

            // reads the entire line
            String str = sc.nextLine();
            // split that line based on space in between
            String[] input = str.split(" ");

            // checks that if first word is Teacher or not
            if(input[0].equals("Teacher")) {

                Teacher t;

                String[] firstLastName = null;
                // if the required conditions are not satisfied it raises an exception
                try {
                    // splitting the name ( second parameter in input line ) , using "," 
                    firstLastName = input[1].split(",");
                    
                    // checking all the conditions
                    if(!(input[1].equals(firstLastName[0]+","+firstLastName[1])) || (input[3].length()!=5) ||(input[4].length()!=10)) {
                        throw new IllegalArgumentException();
                    }
                int ID = Integer.parseInt(input[3]);
                int mobile = Integer.parseInt(input[4].substring(6));
                
                // creating a Teacher object
                t = new Teacher(firstLastName[0]+" "+firstLastName[1], ID, mobile);

                // file path( address ) -- change it according to your computer
                    // if not working properly , create that file in the required location and then give as input
                String file_location = "/home/rahul/Pictures/school.csv";
                // opening file in append mode
                FileWriter fw = new FileWriter(file_location,true);

                // calling method csvPrintln( ) to append into file
                t.csvPrintln(new PrintWriter(fw));

                }
                catch(IllegalArgumentException e) {
                    System.out.println("Enter the input in correct format");
                }
                catch(ArrayIndexOutOfBoundsException e) {
                    System.out.println("Enter the input in correct format");
                }


            }

            // checks that if first word is TA or not
            else if(input[0].equals("TA")) {

                TA ta ;
                String[] firstLastName = null;

                // if the required conditions are not satisfied it raises an exception
                try {
                    // splitting the name ( second parameter in input line ) , using "," 
                    firstLastName = input[1].split(",");
                    if(!(input[1].equals(firstLastName[0]+","+firstLastName[1])) || (input[2].length()!=5) ||(input[4].length()!=10))
                        throw new IllegalArgumentException();

                int sid = Integer.parseInt(input[2]);
                int tid = Integer.parseInt(input[3]);
                int ID = (Math.max(sid,tid));
                long mobile = Long.parseLong(input[4]);
                ta = new TA(firstLastName[0]+" "+firstLastName[1], ID, mobile);

                // // file path( address ) -- change it according to your computer
                String file_location = "/home/rahul/Pictures/school.csv";
                FileWriter fw = new FileWriter(file_location,true);

                ta.csvPrintln(new PrintWriter(fw));

                }
                catch(IllegalArgumentException e) {
                    System.out.println("Enter the input in correct format");
                }
                catch(ArrayIndexOutOfBoundsException e) {
                    System.out.println("Enter the input in correct format");
                }

            }
            // checks that if first word is Student or not
            else if(input[0].equals("Student")) {

                Student s;
                String[] firstLastName = null;
                // if the required conditions are not satisfied it raises an exception
                try {
                    // splitting the name ( second parameter in input line ) , using "," 
                    firstLastName = input[1].split(",");

                    if(!(input[1].equals(firstLastName[0]+","+firstLastName[1])) || (input[2].length()!=5) ||(input[4].length()!=10))
                        throw new IllegalArgumentException();

                int ID = Integer.parseInt(input[2]);
                long mobile = Long.parseLong(input[4]);
                s = new Student(firstLastName[0]+" "+firstLastName[1], ID, mobile);

                    // file path( address ) -- change it according to your computer
                String file_location = "/home/rahul/Pictures/school.csv";
                FileWriter fw = new FileWriter(file_location,true);

                s.csvPrintln(new PrintWriter(fw));
                }
                catch(IllegalArgumentException e) {
                    System.out.println("Enter the input in correct format");
                }
                catch(ArrayIndexOutOfBoundsException e) {
                    System.out.println("Enter the input in correct format");
                }
            }

            // if it is neither Student nor Teacher nor TA  
            else {
                System.out.println("Re enter the above values in correct format");
                // incrementing 'n ' because , if user entered wrong values , that n decrease by 1 in the below updation step
                 // So I am incrementing by 1 here
                n++;
            }

            n--; // updation for while loop
        } // END of while loop

    } // END of main( ) method
} // END of Main class

========================================================================================================================================

========================================================================================================================================

INPUT ( ON CONSOLE )

OUTPUT:

Hey , If you have any doubt ask in comment section I will answer your questions. Thank You !! If you like answer please upvote.


Related Solutions

Create a program in java with the following information: Design a program that uses an array...
Create a program in java with the following information: Design a program that uses an array with specified values to display the following: The lowest number in the array The highest number in the array The total of the numbers in the array The average of the numbers in the array Initialize an array with these specific 20 numbers: 26 45 56 12 78 74 39 22 5 90 87 32 28 11 93 62 79 53 22 51 example...
Write a C++ program for storing information on on a series of balls collected by a...
Write a C++ program for storing information on on a series of balls collected by a person. The balls should have these characteristics: 1. Diameter in mm 2. Color 3. if the texture of the surface is smooth or rough 4. an identification id/number The program should allow the person to enter the values for the balls' attributes as they are entered in a database. The program should then offer the choice to save all new data into a file....
Write a C++ program for storing information on on a series of balls collected by a...
Write a C++ program for storing information on on a series of balls collected by a person. The balls should have these characteristics: 1. Diameter in mm 2. Color 3. if the texture of the surface is smooth or rough 4. an identification id/number The program should allow the person to enter the values for the balls' attributes as they are entered in a database. The program should then offer the choice to save all new data into a file....
Write a Java program to process the information for a bank customer.  Create a class to manage...
Write a Java program to process the information for a bank customer.  Create a class to manage an account, include the necessary data members and methods as necessary.  Develop a tester class to create an object and test all methods and print the info for 1 customer.  Your program must be able to read a record from keyboard, calculate the bonus and print the details to the monitor.  Bonus is 2% per year of deposit, if the amount is on deposit for 5 years...
Write a Java program which asks customer name, id, address and other personal information, there are...
Write a Java program which asks customer name, id, address and other personal information, there are two types of customers, walk-in and credit card. The rates of items are different for both type of customers. System also asks for customer type. Depending upon customer type, it calculates total payment. A credit-card customer will pay 5 % extra the actual price. Use object-oriented concepts to solve the problem. Define as many items and prices as you want. Example Output: Enter Name...
Describe the personal qualities of teachers who increase students’ motivation to learn. Identify the learning climate...
Describe the personal qualities of teachers who increase students’ motivation to learn. Identify the learning climate variables that increase students’ motivation to learn. Explain how different Instructional variables increase students’ motivation to learn.
Create a Java program that receives name, GPA, and graduation year information about a student as...
Create a Java program that receives name, GPA, and graduation year information about a student as user input and prints it to the console. Please use the following constructs in your program: Write your code in a Java class. Define name, GPA and graduation year as variables in our class. Create separate setter and getter methods for those variables. Use your main method, to receive the user input. Initialize an object of the class to call the setter methods and...
Create a program in java using the following information: Trainers at Tom's Athletic Club are encouraged...
Create a program in java using the following information: Trainers at Tom's Athletic Club are encouraged to enroll new members. Write an application that extracts the names of Trainers and groups them based on the number of new members each trainer has enrolled this year. Output is the number of trainers who have enrolled 0 to 5 members, 6 to 12 members, 13 to 20 members, and more than 20 members. Give their names as well as the number of...
Create a short program in Java which contains the below information: - Has one abstract and...
Create a short program in Java which contains the below information: - Has one abstract and two regular classes - Has two interfaces (the two regular classes have to implement at least one interface - At least one regular class must implement both interfaces - The two classes have to extend the abstract class - The abstract class must have a method - At least one interface must have a method - At least two fields in each class, this...
Create a java program that allows people to buy tickets to a concert. Using java create...
Create a java program that allows people to buy tickets to a concert. Using java create a program that asks for the users name, and if they want an adult or teen ticket. As long as the user wants to purchase a ticket the program with "yes" the program will continue. When the user inputs "no" the program will output the customer name, total amount of tickets, and the total price. The adult ticket is $60 and the child ticket...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT