CS Villanova University CSC 1051 www.csc.villanova.edu/~map/1051 Dr. Papalaskari Lab 14 Name:________________________ Checked:______ Objectives: Practice handling exceptions and writing text files. a) Revisit Lab 9 and Project 7 experiment • Run ResponseTimeExperiment.java and experiment with “bad inputs” (e.g., not a number). What is the exception when your input cannot be parsed as a number? Exception: ______________________________________________________________________________________ b) try/catch NumberFormatException Create a try block around the code that parses a response and, using it, computes the outcome. Use a catch clause for NumberFormatException that prints "FAIL: You were supposed to type in a number". c) Write the results of the experiment to a file Let’s now save the results of the experiment to a file. For each subject, the program should create a file using the person’s name as the file name, with “.txt” appended to it, and then output the results of that run (namely, whether they got the question right and the number of milliseconds) to the file, separated by tabs. For example, with the following interaction: ----jGRASP exec: java ResponseTimeExperiment Please enter your name: Megan Hello Megan. Please answer as fast as you can. Hitwhen ready for the question. 96 + 86 = 145 Incorrect. That took 3025 milliseconds Thank you Megan, goodbye. ----jGRASP: operation complete. the program should create a file named Megan.txt with contents: (“false” since the answer was incorrect, with 3025 milliseconds) If, on the other hand, the run did not result in any useful data (i.e., you caught a NumberFromatException), the file should contain: Hints: • Create a PrintWriter object named outfile, using the name that the person entered as the filename. • Use the println() on outfile to output the data collected, i.e., the outcome and milliseconds, separated by a tab. • Don’t forget to close() the file at the end (after all output to the file is done) • Be sure to import java.io.*; • Remember, PrintWriter can throw IOException. We will NOT handle that yet, so you need to list throws IOException in the main() method heading. false 3025 Bad data CS Villanova University CSC 1051 www.csc.villanova.edu/~map/1051 Dr. Papalaskari d) Repeat using your own code from Project 7 • Modify your code from Project 7 to save the results of the experiment to a file and, if necessary, to catch NumberFormatException. For each subject, the program should create a file using the person’s name as the file name, with “.txt” appended to it, as before. The file should contain one line corresponding to each question, with the results and the number of milliseconds, unless that question did not result in usable data (i.e., the program had to handle a NumberFormatException), in which case the corresponding line in the file should contain “bad data”. • Run the experiment using yourself and your partner as subjects and verify that the corresponding files were created correctly. e) What if the file cannot be created? • Can you figure out how to crash your programs (ie, cause FileNotFoundException)? This can happen if the name entered by the user cannot be used by your operating system to create a file with that name. Play around with the program using different inputs for your name (Hint: try various symbols and non-alpha characters), until you cause this exception and make a note of the input here: Bad file name that crashed the program: _________________________________________________ Message: _____________________________________________________________________________________ Now let’s try/catch it: • First, separate the PrintWriter declaration from the instantiation: PrintWriter outfile; // declaration outFile = new PrintWriter( . . . ); // instantiation • Next, place the instantiation for the PrintWriter in a try block, and catch IOException (that will catch FileNotFoundException and others as well). In the catch, handle the exception as follows: o outFile = new PrintWriter(System.out); o print a warning on standard output, such as: WARNING: Unable to create file (*name of file*). Data output to System.out. To summarize: The experiment proceeds as before. If no IOException occurs, the file will be created; if that is impossible (i.e., an exception occurs), the program will recover and proceed after a warning, and the contents that would have normally gone to the file will instead get printed at the end of the run, after all the other output. CS Villanova University CSC 1051 www.csc.villanova.edu/~map/1051 Dr. Papalaskari e) What if your subject is prone to obscenity? Sometimes programs need to respond to rude or offensive user behavior. Here we will handle this situation by throwing an exception, so that the program aborts when the user enters a forbidden word as their name. Here is how to do this: • Create a class BadWordException.java that extends Exception: //******************************************************************** // BadWordException.java Author: M A Papalaskari // Represents an exceptional condition for using bad words. //******************************************************************** public class BadWordException extends Exception { //----------------------------------------------------------------- // Sets up the exception object with a particular message. //----------------------------------------------------------------- BadWordException(String message) { super(message); } } • Create a file “excusemyfrench.txt” of banned words. Try it first with just a few words (such lists are available free on the web, you can download one later). • In the ResponseTimeExperiment program (or use your own program from Project 7), check that the name entered is not a banned word before creating a file with the name of the person. Below is some code to do this: run through the banned words file, comparing the name with each word. If you get a match, punish them by throwing an exception! Scanner badWords = new Scanner(new File("excusemyfrench.txt")); while (badWords.hasNext()) if (name.equals(badWords.next())) throw (new BadWordException("Watch your tongue")); Notes: 1) By default, your BadWordException is a checked exception and thus needs to be listed with a throws clause in the heading of your main method. 2) We are again faced with the possibility of an IOException, this time for the input file excusemyfrench.txt. Handle it by placing the above code inside a try block and use a catch clause such as: catch (IOException e) { System.out.println("Warning: excusemyfrench.txt missing. "); System.out.println("Not checking input for obscenity"); } CS Villanova University CSC 1051 www.csc.villanova.edu/~map/1051 Dr. Papalaskari Lab 14 Comments Name:________________________ Comments on this lab, please: What was the most valuable thing you learned in this lab? What did you like best about this lab? Was there any particular problem? Do you have any suggestions for improving this lab as an effective learning experience?