In: Computer Science
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
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.