home / study / questions and answers / engineering / computer science / write an
ID: 3771491 • Letter: H
Question
home / study / questions and answers / engineering / computer science / write an application to save, retrieve and modify ... Question Write an application to save, retrieve and modify the student survey data. This application is divided into 2 module Student module and Instructor module. (In Java, eclipse)
Student Module:
• Students will be ask to enter survey data (StudentId, LastName, FirstName, Street, City, State)
• Ask Students to confirm if the data entered is correct. (Y/N)
• Survey data should be saved in a text file in alphabetical order by LastName (use either ArraySortedList or RefSortedList). The directory to save your file is User/SurveyDir/.
Instructor Module:
o Instructor should be able to retrieve the survey entry by StudentId and/or LastName from the file.
o Instructor should be able to remove an entry using StudentId or LastName from the file.
Explanation / Answer
import java.awt.*; // Button, Event, Font, Frame, Panel, // Dialog, Text import java.io.*; // InputStream, OutputStream import java.lang.*; // Integer, Thread, Runnable (req'd for Thread) import java.net.*; // Socket, ServerSocket, InetAddress import java.util.*; // Calendar, Date, StringTokenizer // import corejava.*; // Format /*------------------------------------------------------------------*/ /*------------------------------------------------------------------*/ public class Survey { // Class Constants public static final int PROF = 0; public static final int STU = 1; // Professor and Student Data Members public static AlarmClock clock; // timer public static Frame display; // user's display public static int num_clients = 0; // cummulative connections accepted public static String question = ""; public static int responses_no = 0; // Number of "No" responses to Survey question public static int responses_yes = 0; // Number of "Yes" responses to Survey question public static String results = ""; // Survey results public static int user; // PROF or STU - set in checkUsage() public static int mins; // displayed // init in main() // decremented in display.updateTimeFields() public static int secs; // displayed // init in main() // decremented in display.updateTimeFields() // Professor-specific Data Members public static long epoch; // When PROF'S timer starts in .001 seconds public static ServerSocket listener; // init in main() public static int survey_duration; // In minutes - set in checkUsage() public static int secs_remaining; // set in AlarmClock // Student-specific Data Members public static int client_response = -1; // Student's response // 0 => No // 1 => yes public static Socket client_sock; // Professor's State Variables public static boolean question_ready = false; public static boolean send_question = false; public static boolean question_sent = false; public static boolean send_results = false; public static boolean results_sent = false; public static boolean time_left = true; // changed by AlarmClock.run() // accessed by runServer() // Student's State Variables public static boolean got_question = false; // changed in runClient() public static boolean send_response = false; // changed by CreateDisplay() public static boolean response_sent = false; // changed in runClient() public static boolean got_results = false; // changed in runClient() public static boolean stu_quit = false; // changed in CreateDisplay() /*-------------------------------------*/ // Called by: cmd line // Calls: checkUsage(), CreateDisplay(), runServer() public static void main (String[] args) { // check usage checkUsage(args); if (user == PROF) System.out.println ("Prof started program"); else System.out.println ("Student started program"); // create the display mins = survey_duration; secs = 0; display = new CreateDisplay (); display.resize (600, 500); display.show(); // create server process if Prof started program if (user == PROF) { secs_remaining = survey_duration * 60; // decremented by clock try { listener = new ServerSocket (0); String hostname = listener.getInetAddress().getLocalHost().toString(); System.out.println ("Let each student type: java Survey "+ hostname +" "+ listener.getLocalPort()); } catch (IOException e) { System.out.println ("Server() - IOException: Can't get Server socket"); System.exit (-1); } runServer (); } // end if user == PROF // create client process if Student started program else { try { client_sock = new Socket (args[0], Integer.parseInt ((args[1]).trim())); System.out.println ("Client connected to Server. Socket = " + client_sock.getLocalPort()); } catch (UnknownHostException e) { System.err.println ("Error creating new client socket: " + e.getMessage()); System.exit (-1); } catch (IOException e) { System.err.println ("Error creating new client socket: " + e.getMessage()); System.exit (-1); } runClient (); } // end if user == STU } // end main() /*-------------------------------------*/ // Called by: checkUsage() // Calls: -- public static void printUsage() { System.err.print (" Professor/Server USAGE: java Survey "); System.err.print ("Student/Client USAGE: java Survey "); System.exit (-1); } // end printUsage() /*-------------------------------------*/ // Called by: main() // Calls: printUsage() public static void checkUsage (String[] args) { // CASE of too few arguments. if (args.length == 0) { System.err.println (" Too few arguments."); printUsage(); } /* Case of attempted Professor/Server usage e.g. java survey */ else if (args.length == 1) { if ((survey_duration = Integer.parseInt ((args[0]).trim())) > 0) user = PROF; else { System.err.println (" Couldn't convert '" + args[0] + "' to 1 minute or greater."); printUsage (); } } /* Case of attempted Student/Client usage e.g. java survey */ else if (args.length == 2) { if (Integer.parseInt ((args[1]).trim()) > 0) user = STU; else { System.err.println (" Couldn't convert '" + args[1] + "' to a port number."); printUsage (); } } // CASE of too many arguments. else { System.err.println (" Too many arguments"); printUsage(); } } // end checkUsage () /*-------------------------------------*/ // Called by: main() // Calls: ServeSurveyClient () public static void runServer () { String str; while (time_left) { try { // accept the new connection request Socket clientSocket = listener.accept(); // increment number of connections accepted num_clients++; // reset the Professor's "Cummulative Connections" field str = "" + num_clients; CreateDisplay.totL.setText (str); System.out.println ("Server accepted new client at '" + clientSocket.getLocalPort() + "'."); // serve the new Client (class calls start()) new ServeSurveyClient (clientSocket); } catch (IOException e) { // thrown by accept() System.out.println ("Server() - IOException: "+e.getMessage()+"."); System.exit (-1); } } // end while } // end void runServer() /*-------------------------------------*/ // Called by: main() // Calls: public static void runClient() { DataInputStream sock_in; PrintStream sock_out; String in_buff; String str; PostDialog pd; StringTokenizer t; String msg_type; try { // get the Student's input and output streams sock_in = new DataInputStream (client_sock.getInputStream()); sock_out = new PrintStream (client_sock.getOutputStream()); // tell Server we're waiting for question and // wait for question to arrive while (!got_question) { sock_out.println ("ALIVE "); in_buff = sock_in.readLine(); if (in_buff == null) { pd = new PostDialog (display, CreateDisplay.MSGS, 16, 17, 'I'); pd.show(); closeSocket (client_sock); return; } System.out.println ("Server sent: " + in_buff); t = new StringTokenizer (in_buff, "|"); msg_type = t.nextToken(); if (msg_type.equals("SURVEY")) { got_question = true; question = t.nextToken(); System.out.println ("Survey question is: " + question); secs_remaining = Integer.parseInt (t.nextToken()); // time lag System.out.println ("Survey duration is: " + Survey.secs_remaining + " secs."); mins = secs_remaining/60; secs = secs_remaining%60; CreateDisplay.questionL.setText (question); clock = new AlarmClock (secs_remaining * 1000); clock.start(); } } // end while (!got_question) // collect and evaluate Server msgs while we wait for // student to "send" the response do { sock_out.println ("ALIVE "); in_buff = sock_in.readLine(); if (in_buff == null) { pd = new PostDialog (display, CreateDisplay.MSGS, 16, 17, 'I'); pd.show(); closeSocket (client_sock); return; } System.out.println ("Survey question is: " + question); t = new StringTokenizer (in_buff, "|"); msg_type = t.nextToken(); if (msg_type.equals("RESULTS")) { got_results = true; time_left = false; num_clients = Integer.parseInt(t.nextToken()); responses_yes = Integer.parseInt (t.nextToken()); responses_no = Integer.parseInt (t.nextToken()); System.out.println ("Survey results are: tot=" + num_clients + ", yes=" + responses_yes + ", no=" + responses_no); CreateDisplay.totL.setText (question); str = "" + num_clients; CreateDisplay.totL.setText (str); str = "" + responses_yes; CreateDisplay.yesL.setText (str); str = "" + responses_no; CreateDisplay.noL.setText (str); mins = 0; secs = 0; } } while (!got_results && time_left && !send_response); // check to see if the results arrived before student // had a chance to send her response if (got_results) { pd = new PostDialog (display, CreateDisplay.MSGS, 13, 15, 'I'); pd.show(); closeSocket (client_sock); clock.stop(); return; } // send the Student's response if (time_left && send_response) { if (client_response == 1) str = "Yes"; else str = "No"; sock_out.println (str + " "); response_sent = true; } // Wait for results to arrive while (time_left && !got_results) { in_buff = sock_in.readLine(); if (in_buff == null) { pd = new PostDialog (display, CreateDisplay.MSGS, 16, 17, 'I'); pd.show(); closeSocket (client_sock); clock.stop(); return; } t = new StringTokenizer (in_buff, "|"); msg_type = t.nextToken(); if (msg_type.equals("RESULTS")) { got_results = true; time_left = false; num_clients = Integer.parseInt(t.nextToken()); responses_yes = Integer.parseInt (t.nextToken()); responses_no = Integer.parseInt (t.nextToken()); System.out.println ("Survey results are: tot=" + num_clients + ", yes=" + responses_yes + ", no=" + responses_no); str = "" + num_clients; CreateDisplay.totL.setText (str); str = "" + responses_yes; CreateDisplay.yesL.setText (str); str = "" + responses_no; CreateDisplay.noL.setText (str); mins = 0; secs = 0; } sock_out.println ("ALIVE "); } // end while (time_left && !got_results) } // end try catch (IOException e) { System.err.println (e.getMessage()); pd = new PostDialog (display, CreateDisplay.MSGS, 16, 17, 'I'); pd.show(); closeSocket (client_sock); return; } System.out.println ("Closing Student's socket to Server since results received."); closeSocket (client_sock); return; } // end void runClient () /*-------------------------------------*/ // Called by: ServeSurveyClient(), runClient() // Calls: -- public static void closeSocket (Socket s) { System.out.println ("Closing Client socket "+ s.getLocalPort()); try { s.close(); } catch (IOException e) { System.out.println (e); } } // end closeSocket() } // end public class Survey /*------------------------------------------------------------------*/ /*------------------------------------------------------------------*/ class CreateDisplay extends Frame { // class constants public static final String[] MSGS = { "The Survey Results haven't been posted.", // 0 "You cannot quit!", // 1 "You haven't provided a question yet!", // 2 "The question can't be sent.", // 3 "You already sent your question!", // 4 "The question hasn't arrived yet.", // 5 "You can't send a response!!", // 6 "You already sent your response!.", // 7 "You must first click 'Yes' or 'No'!", // 8 "Time in which responses could be", // 9 "submitted has EXPIRED. Survey results", // 10 "will be promulgated momentarily.", // 11 "You may quit now.", // 12 "Survey responses are no longer being", // 13 "accepted. The alloted time has EXPIRED.", // 14 "You should quit.", // 15 "Your connection to the Survey server", // 16 "has been lost. You should quit.", // 17 }; public static final String[] QUESTIONS = { "Do you really want to quit?" }; // CreateDisplay class variables public Panel panel1; // survey question area public Panel panel2; // students' response area public Panel panel3; // send and quit button area public Panel panel4; // results area1/2 -- tot connections public Panel panel5; // results area2/2 -- yes and no answers public Panel panel6; // time remaining (00:00 -- mins, sec) public Button sendB; // send button public Button quitB; // quit button public Checkbox yesCB; // yes box public Checkbox noCB; // no box public static Label questionL; // stu's posted question public static TextField questionTF; // prof's question field public static Label yesL; // number of yes responses public static Label noL; // number of no responses public static Label totL; // cummulative # of Client Connections public static TextField timeTF; // time remaining field in panel6 // Class Constructor public CreateDisplay () { GridBagLayout gbl; GridBagConstraints gbc; // Create the display gbl = new GridBagLayout(); setLayout (gbl); gbc = new GridBagConstraints(); gbc.weightx = 100; // allocate 100% extra space per column gbc.weighty = 14.2857; // allocate 1/7 extra space per row gbc.fill = GridBagConstraints.NONE; // don't fill the entire pane gbc.anchor = GridBagConstraints.NORTHWEST;// left-justify the panel's stuff // Grid extent is 1 column by 7 rows // Add components (panels) top to bottom. // INIT PROF VS. STU COMPONENTS initLabels (); // SET UP PANEL1 panel1 = newPanel(); panel1.add (new Label ("Survey Question: ")); if (Survey.user == Survey.PROF) panel1.add (questionTF); else panel1.add (questionL); add (panel1, gbl, gbc, 0, 0, 1, 1); // place at (0,0) // takes up 1 col, 1 row // SET UP PANEL2 panel2 = newPanel(); if (Survey.user == Survey.STU) { panel2.add (new Label ("Check one answer: ")); panel2.add (yesCB); panel2.add (new Label (" ")); panel2.add (noCB); } gbc.anchor = GridBagConstraints.WEST; // left-justify panel's stuff add (panel2, gbl, gbc, 0, 1, 1, 1); // SET UP PANEL3 panel3 = newPanel(); panel3.add (sendB = new Button ("Send")); panel3.add (new Label (" ")); panel3.add (quitB = new Button (" Quit ")); gbc.anchor = GridBagConstraints.CENTER;// center the panel's stuff add (panel3, gbl, gbc, 0, 2, 1, 1); // SET UP PANEL4 panel4 = newPanel(); panel4.add (new Label ("Cummulative Connections: ")); panel4.add (totL); add (panel4, gbl, gbc, 0, 3, 1, 1); // gbc.anchor == CENTER // SET UP PANEL5 panel5 = newPanel(); panel5.add (new Label ("Yes Reponses: ")); panel5.add (yesL); panel5.add (new Label (" ")); panel5.add (new Label ("No Responses: ")); panel5.add (noL); add (panel5, gbl, gbc, 0, 4, 1, 1); // gbc.anchor == CENTER // SET UP PANEL6 panel6 = newPanel(); panel6.add (new Label ("Time Remaining: ")); panel6.add (timeTF); panel6.add (new Label (" (m:ss) ")); gbc.anchor = GridBagConstraints.EAST; // left-justify panel's stuff add (panel6, gbl, gbc, 0, 5, 1, 1); } // end CreateDisplay() constructor // Permits window to close if user clicks on the "X" // in the NE corner of window public boolean handleEvent (Event evt) { PostDialog pd; if (evt.id == Event.WINDOW_DESTROY && evt.target == this) { // Professor can't quit if he hasn't sent the Survey results if (Survey.user == Survey.PROF && Survey.num_clients > 0 && Survey.results_sent == false) { pd = new PostDialog (this, MSGS, 0, 1, 'I'); pd.show (); } else { // Prof has sent the Survey results, or, // a Student wants to shut down the display. // This dialog can change the value of // CreateDisplay.wants_to_quit pd = new PostDialog (this, QUESTIONS, 0, 0, 'Q'); pd.show (); } return true; } return super.handleEvent (evt); } public boolean action (Event evt, Object arg) { PostDialog pd; if (arg.equals (" Quit ")) { // Case that Prof can't quit because the // Survey results haven't been sent yet if (Survey.user == Survey.PROF && Survey.num_clients > 0 && Survey.results_sent == false) { pd = new PostDialog (this, MSGS, 0, 1, 'I'); pd.show (); } else { // Case that Prof has sent the Survey results, or, // a Student wants to shut down the display. pd = new PostDialog (this, QUESTIONS, 0, 0, 'Q'); pd.show (); } } // end "Quit" else if (arg.equals ("Send")) { if (Survey.user == Survey.PROF) { // Professor hit "Send" if (Survey.send_question == true) { // Case that Prof has already sent the question. pd = new PostDialog (this, MSGS, 4, 4, 'I'); pd.show (); } else { // Case that Prof hasn't sent the question. Survey.question = questionTF.getText().trim(); if (Survey.question.equals ("(Replace this with your question!!!)") || Survey.question.length () == 0) { // Case that Prof hasn't provided a question. pd = new PostDialog (this, MSGS, 2, 3, 'I'); pd.show (); } else { Survey.send_question = true; questionTF.setEditable (false); Date date = new Date(); Survey.epoch = date.getTime(); // set the start time Survey.clock = new AlarmClock (Survey.survey_duration * 60 * 1000); Survey.clock.start(); } } } // end Prof hit "Send" // Student hit "Send" else { if (Survey.got_results == true || Survey.time_left == false) { pd = new PostDialog (this, MSGS, 13, 15, 'I'); pd.show(); } else if (Survey.got_question == false) { // Case that the question hasn't arrived. pd = new PostDialog (this, MSGS, 5, 6, 'I'); pd.show(); } else if (Survey.send_response == true) { // Case that Student already sent response. pd = new PostDialog (this, MSGS, 7, 7, 'I'); pd.show(); } else if (Survey.client_response == -1) { // Case that Student doesn't have a response // selected. pd = new PostDialog (this, MSGS, 8, 8, 'I'); pd.show(); } else { Survey.send_response = true; // Since Student is ready to send her response, // fix the current checkbox settings so // no changes can be made. if (Survey.client_response == 1) { // Case of "Yes" response yesCB.setState (true); noCB.setState (false); } else { yesCB.setState (false); noCB.setState (true); } } } // end Stu hit "Send" } // end "Send" else if (evt.target.equals(yesCB)) { if (Survey.got_results == true) { pd = new PostDialog (this, MSGS, 13, 15, 'I'); pd.show(); } Survey.client_response = 1; System.out.println ("Student selected 'yes'."); } else if (evt.target.equals(noCB)) { if (Survey.got_results == true) { pd = new PostDialog (this, MSGS, 13, 15, 'I'); pd.show(); } Survey.client_response = 0; System.out.println ("Student selected 'no'."); } return true; } public static void updateTimeField () { PostDialog pd; // Had to make method 'static' so I could call from // AlarmClock instance if (Survey.mins == 0 && Survey.secs == 0) return; else Survey.secs--; if (Survey.secs >= 10) timeTF.setText (Survey.mins + ":" + Survey.secs); else if (Survey.secs >= 0) timeTF.setText (Survey.mins + ":0" + Survey.secs); else if (Survey.mins >= 1) { // where Survey.secs == -1 Survey.mins--; Survey.secs = 59; timeTF.setText (Survey.mins + ":59"); } } // end updateTimeField() private void add (Component c, GridBagLayout gbl, GridBagConstraints gbc, int x, int y, int num_cols, int num_rows) { gbc.gridx = x; gbc.gridy = y; gbc.gridwidth = num_cols; gbc.gridheight = num_rows; gbl.setConstraints (c, gbc); add(c); } // end add () private Panel newPanel () { Panel p; if (null == (p = new Panel())) { System.err.print ("Insufficient mem to create new panel. Exiting. "); System.exit (-1); } p.setLayout (new FlowLayout()); return p; } private void initLabels () { CheckboxGroup cbg; if (Survey.user == Survey.PROF) { setTitle ("Professor's Display for Survey"); questionTF = new TextField ("(Replace this with your question!!!)", 45); questionTF.setEditable (true); totL = new Label("0 "); // to permit setText later yesL = new Label ("0 "); noL = new Label ("0 "); timeTF = new TextField (Survey.survey_duration + ":00", 7); } else { // Survey.user == Survey.STU setTitle ("Student's Display for Survey"); questionL = new Label ("(Waiting for survey question) "); cbg = new CheckboxGroup(); yesCB = new Checkbox ("Yes", cbg, false); noCB = new Checkbox ("No", cbg, false); totL = new Label("---"); yesL = new Label ("---"); noL = new Label ("---"); timeTF = new TextField (" ", 7); } timeTF.setEditable (false); } // end initLabels() } // end class CreateDisplay /*------------------------------------------------------------------*/ /*------------------------------------------------------------------*/ // By default, class is private class PostDialog extends Dialog { private Panel msg_panel; private Panel button_panel; private Button noB; private Button yesB; private Button okB; private char msg_type; // Class Constructor public PostDialog ( Frame parent, String[] msg, int beg_index, int end_index, char mType) { super (parent, "", true); // don't title the dialog box // set modal = true // create the message panel for the dialog msg_panel = new Panel (); for (int i = beg_index; iRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.