Name: Checked: Preparation: Investment Calculator with input and output to text files Submit through Blackboard by 8:00am the morning of Lab.

Similar documents
Name: Checked: Preparation: Write the output of DeckOfCards.java to a text file Submit through Blackboard by 8:00am the morning of Lab.

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name: KEY. Question Value Score

Lab 6. Name: Checked:

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name

Name: Checked: Preparation: Response time experiment accessing the system clock

Name: Checked: Preparation: Response time experiment accessing the system clock

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

File I/O and Exceptions

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

CS159. Nathan Sprague

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 11, Name: KEY

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Lab 5: Java IO 12:00 PM, Feb 21, 2018

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

File I/O Array Basics For-each loop

COMP-202 Unit 9: Exceptions

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

Introduction to Computer Science II CS S-22 Exceptions

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions

BBM 102 Introduction to Programming II Spring Exceptions

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Exceptions and Libraries

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

I/O Streams. COMP 202 File Access. Standard I/O. I/O Stream Categories

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP File Access 1

BBM 102 Introduction to Programming II Spring 2017

Input-Output and Exception Handling

Exceptions. CSC207 Winter 2017

COMP-202 Unit 9: Exceptions

Administrivia. CPSC Winter 2008 Term 1. Department of Computer Science Undergraduate Events

Exceptions - Example. Exceptions - Example

Happy Cinco de Mayo!!!!

Simple Java Input/Output

Programming II (CS300)

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

Happy Cinco de Mayo!!!!

CS159. Nathan Sprague

CS112 Lecture: Exceptions and Assertions

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP 202 File Access 1

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Defensive Programming

Exceptions and Design

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

When we reach the line "z = x / y" the program crashes with the message:

Recitation: Loop Jul 7, 2008

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

Introduction Unit 4: Input, output and exceptions

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

Programming II (CS300)

Computer Science is...

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Unit 10: exception handling and file I/O

File class in Java. Scanner reminder. File methods 10/28/14. File Input and Output (Savitch, Chapter 10)

Chapter 4: Loops and Files

COSC Exception Handling. Yves Lespérance. Lecture Notes Week 10 Exception Handling

Advanced Java Concept Unit 1. Mostly Review

Intro to Computer Science II. Exceptions

Chapter 4: Loops and Files

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.

16-Dec-10. Consider the following method:

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name: Question Value Score

Fundamentos de programação

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

More on Exception Handling

Full file at Chapter 2 - Inheritance and Exception Handling

Handout 4: Version Control Reference

10/8/2018 Programming Data Structures. class diagram for assignment 08 review: polymorphism review: exception new: File I/O

Exceptions Programming 1 C# Programming. Rob Miles

Exceptions. Exceptions. Exceptional Circumstances 11/25/2013

CSCI 261 Computer Science II

Fundamentals of Object Oriented Programming

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

Excep&ons and file I/O

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

ECE 122. Engineering Problem Solving with Java

For more details on SUN Certifications, visit

Lab 1: Introduction to Java

Starting Out with Java: From Control Structures Through Objects Sixth Edition

CS S-22 Exceptions 1. Running a web server, don t want one piece of bad data to bring the whole thing down

An exception is simply an error. Instead of saying an error occurred, we say that an.

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

CSE 143 Java. Exceptions 1/25/

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Fall 2017 CISC124 10/1/2017

Name: Checked: Preparation: Use variables to output a personalized message

CSCI 200 Lab 2 Inheritance, Polymorphism & Data Streams

Exception Handling. Exception Handling

Reminder. Topics CSE What Are Exceptions?! Lecture 11 Exception Handling

Errors and Exceptions

CS1092: Tutorial Sheet: No 3 Exceptions and Files. Tutor s Guide

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

Input/Output (I/0) What is File I/O? Writing to a File. Writing to Standard Output. CS111 Computer Programming

Assignment 17 Deadline: Oct pm COSC211 CRN15376 Session 14 (Oct. 29)

CISC 323 (Week 9) Design of a Weather Program & Java File I/O

CS 151. Exceptions & Javadoc. slides available on course website. Sunday, September 9, 12

Transcription:

Lab 14 Name: Checked: Objectives: Practice handling exceptions and writing text files. Preparation: Investment Calculator with input and output to text files Submit through Blackboard by 8:00am the morning of Lab. 1. Review your code for Project 4, InvestmentCalculator.java (you may have used a different name, that is ok). Save a copy in your Lab 14 folder. 2. Run the program a few times to remind yourself of its functionality and the form of input that it requires; then create an input text file with input in the correct format (be sure to save the file with.txt extension). Modify the code so that its input comes from your file (instead of being typed interactively). Be sure to remove (or comment out) all the prompts for the user input; the only output you want is the actual output of the program (i.e., the table of results and the number of years it takes to reach the target amount). Make sure this works before proceeding. Reminders: Don t forget to import java.io.*; Remember to add throws IOException in the main() method heading. 3. Modify the code so that it creates an output file with a file name that is obtained from the user. Reminders: Prompt the user to enter a file name. Create a PrintWriter object named outfile, using the name that the person entered as the filename. Modify the code so that instead of using System.out.println( ) it uses outfile.println( ) to output to the file. Don t forget to close() the file at the end (after all output to the file is done) 3. Run the code three times, obtaining three text files. 4. Submit the three output files along with your code.

Part A: try/catch NumberFormat 1. Using the code for ResponseTimeExperiment, experiment with bad inputs until you cause NumberFormatException. Note the error message generated: 2. Is NumberFormatException a checked or unchecked exception? 3. With your partner, look up NumberFormatException in our lecture slides and the Java API. Note the classes in between: Exception NumberFormatException 4. We will now prepare to handle the NumberFormatException. The problematic code needs to go inside a try block. Note that it should include the failing step (input a number for the answer), plus all the steps that cannot be completed when that input step fails see steps inside dashed line box in the algorithm. Use a catch block to print a message, e.g., "FAIL: You were supposed to input a number". 5. Add some more code in the catch so that it also adds a line with an asterisk ( * ) to the output file. Thus, for example, the output file corresponding to a particular run might look like this: 1 2529 0 1875 * 1 2773 In this run the subject entered an invalid answer for the 3 rd question(as opposed to a numeric answer that was correct (1) or incorrect (0)). Algorithm: (from Lab 6) 1. input name 2. print personalized welcome message & instructions A. numcorrect = 0 B. totaltime = 0 C. repeat 4 times: 3. a = random int 4. b = random int 5. starttime = current time 6. print question using a, b 7. input answer 8. endtime = current time 9. outcome = 1 or 0 (answer is correct or incorrect) 10. reactiontime = endtime starttime D. totaltime = totaltime + reactiontime 11. print outcome as Correct or Incorrect E. numcorrect = numcorrect + outcome F. averagetime = totaltime/4 G. print averagetime H. print numcorrect 12. print goodbye

Part B: IOException 1. What if the file cannot be created? Can you figure out how to crash your program (i.e.,, cause a kind of IOException to be thrown (most likely FileNotFoundException) This can happen if the name entered by the user cannot be used by your 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: 2. 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, use the following code to handle the exception: outfile = new PrintWriter(System.out); 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 from the exception: 1) issue a warning and 2) proceed as before, but the contents that would have normally gone to the file will instead be displayed on the screen. Part C: 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. In the InvestmentCalculator program, we will check that the file name entered is not a banned word before creating a file with the name. Follow these steps: 1. Create a class BadWordException.java that extends Exception. Here is the code:

//******************************************************************** // 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); Save this code in your Lab 14 folder. Compile it. (You should not try to run it.) 2. Create a file excusemyfrench.txt of banned words. Try first with just a few words (such lists are available free on the web, you can download one later). 3. In the new version of InvestmentCalculator.java, in the heading of the main() method add: throws BadWordException, IOException 4. Now in InvestmentCalculator.java we can check that the name entered is not a banned word. We will do this after obtaining the name from the user, by running through the banned words file, comparing the name with each word in the file. If a match is found, we punish them by throwing an exception! (i.e., the program terminates). Here is some code to do this: Scanner badwords = new Scanner(new File("excusemyfrench.txt")); /**/ while (badwords.hasnext()) if (name.equals(badwords.next())) throw (new BadWordException("Watch your tongue")); 5. Note that we are also faced with the possibility of an IOException, this time for the input file excusemyfrench.txt (the file may be missing). Move the file temporarily to a different folder and run the program again to observe what happens. 6. Let s handle the problem of this missing excusemyfrench.txt file. Place the code that sets up the Scanner and checks for matches (code given in 4, above) inside a try block with a catch clause that issues a warning and omits the check for bad words: catch (IOException e) System.out.println("Warning: excusemyfrench.txt missing. "); System.out.println("Not checking input for obscenity"); In other words, if the file excusemyfrench.txt is missing, the program will function normally, except that it will not be checking for banned words.

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?