Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: __ King Abdulaziz University Faculty of Computing and Information Systems Spring Term 2012/1433 Course Code: CPCS-203 Course Name: Programming II _________________________________________________________________ Objectives In this chapter you will learn: How exception and error handling works. To use try, throw and catch to detect, indicate and handle exceptions, respectively. To use the finally block to release resources. How stack unwinding enables exceptions not caught in one scope to be caught in another scope. How stack traces help in debugging. How exceptions are arranged in an exception class hierarchy. To declare new exception classes. To create chained exceptions that maintains complete stack trace information. What files are and how they are used to retain application data between successive executions. To create, read, write and update files. To use class File to retrieve information about files and directories. The Java input/output stream class hierarchy. The differences between text files and binary files. Sequential-access file processing. To use classes Scanner and Formatter to process text files. To use classes FileInputStream and FileOutputStream to read from and write to files. To use classes ObjectInputStream and ObjectOutputStream to read objects from and write objects to files. To use a JFileChooser dialog. 1|Page CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: __ Prelab Activity: Programming Output For each of the given program segments, read the code and write the output in the space provided below each program. [Note: Do not execute these programs on a computer.] 1. What is output by the following application? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 public class Test { public static String lessThan100( int number ) throws Exception { if ( number >= 100 ) throw new Exception( "Number too large." ); } return String.format( "The number %d is less than 100", number ); public static void main( String args[] ) { try { System.out.println( lessThan100( 1 ) ); System.out.println( lessThan100( 22 ) ); System.out.println( lessThan100( 100 ) ); System.out.println( lessThan100( 11 ) ); } catch( Exception exception ) { System.out.println( exception.toString() ); } } // end main method } // end class Test Your answer: The number 1 is less than 100 The number 22 is less than 100 java.lang.Exception: Number too large. 2|Page CPCS 203 Student Name: _____________________________ 2. What is output by the following program? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 public class Test { public static void method3() throws RuntimeException { throw new RuntimeException( "RuntimeException occurred in method3" ); } public static void method2() throws RuntimeException { try { method3(); } catch ( RuntimeException exception ) { System.out.printf( "The following exception occurred in method2\n%s\n", exception.toString() ); throw exception; } } // end method2 public static void method1() throws RuntimeException { try { method2(); } catch ( RuntimeException exception ) { System.out.printf( "The following exception occurred in method1\n%s\n", exception.toString() ); throw exception; } } // end method1 public static void main( String args[] ) { try { method1(); } catch ( RuntimeException exception ) { System.out.printf( "The following exception occurred in main\n%s\n", exception.toString() ); } } // end main } // end class test Your answer: The following exception occurred in method2 java.lang.RuntimeException: RuntimeException occurred in method3 The following exception occurred in method1 java.lang.RuntimeException: RuntimeException occurred in method3 The following exception occurred in main java.lang.RuntimeException: RuntimeException occurred in method3 3|Page Lab sheet 5 Section: __ CPCS 203 Student Name: _____________________________ 3. What is output by the following program? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public class Test { public static String divide( int number1, int number2 ) { return String.format( "%d divided by %d is %d", number1, number2, ( number1 / number2 ) ); } public static void main( String args[] ) { try { System.out.println( divide( 4, 2 ) ); System.out.println( divide( 20, 5 ) ); System.out.println( divide( 100, 0 ) ); } catch( Exception exception ) { System.out.println( exception.toString() ); } } // end main } // end class Test Your answer: 4 divided by 2 is 2 20 divided by 5 is 4 java.lang.ArithmeticException: / by zero 4|Page Lab sheet 5 Section: __ CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: __ 4. What is output by the following program if the user enters the values 3 and 4.7? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import javax.swing.JOptionPane; public class Test { public static String sum( int num1, int num2 ) { return String.format( "%d + %d = %d", num1, num2, ( num1 + num2 ) ); } public static void main( String args[] ) { int number1; int number2; try { number1 = Integer.parseInt( JOptionPane.showInputDialog( "Enter an integer: " ) ); number2 = Integer.parseInt( JOptionPane.showInputDialog( "Enter another integer: " ) ); System.out.println( sum( number1, number2 ) ); } catch ( NumberFormatException numberFormatException ) { System.out.println( numberFormatException.toString() ); } } // end main method } // end class Test Your answer: java.lang.NumberFormatException: For input string: "4.7" 5|Page CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: __ Prelab Activity: Correct the Code Determine if there is an error in each of the following program segments. If there is an error, specify whether it is a logic error or a compilation error, circle the error in the program and write the corrected code in the space provided after each problem. If the code does not contain an error, write “no error.” [Note: There may be more than one error in each program segment.] 5. The following code segment should catch only NumberFormatExceptions and display an error message dialog if such an exception occurs: catch ( Exception exception ) JOptionPane.showMessageDialog( this, "A number format exception has occurred", "Invalid Number Format", JOptionPane.ERROR_MESSAGE ); 1 2 3 4 Your answer: catch ( NumberFormatException numberFormatException ) { JOptionPane.showMessageDialog( this, "A number format exception has occurred", "Invalid Number Format", JOptionPane.ERROR_MESSAGE ); } 1 2 3 4 5 6 • • The catch handler should declare that it catches NumberFormatExceptions. This is a logic error. The body of the catch handler must be enclosed in braces. This is a syntax error. 6. In the following code segment, assume that method1 can throw both NumberFormatExceptions and ArithmeticExceptions. The following code segment should provide appropriate exception handlers for each exception type and should display an appropriate error message dialog in each case: 1 2 3 4 5 6 7 8 9 10 try method1(); catch ( NumberFormatException n, ArithmeticException a ) { JOptionPane.showMessageDialog( this, String.format( "The following exception occurred\n%s\n%s\n", n.toString(), a.toSting() ), "Exception occurred", JOptionPane.ERROR_MESSAGE ); } 6|Page CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: __ Your answer: try { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 method1(); } catch ( NumberFormatException n ) { JOptionPane.showMessageDialog( this, "The following exception occurred \n" + n.toString(), "Exception occurred", JOptionPane.ERROR_MESSAGE ); } catch ( ArithmeticException a ) { JOptionPane.showMessageDialog( this, "The following exception occurred \n" + a.toString(), "Exception occurred", JOptionPane.ERROR_MESSAGE ); } • The code in the try block must be enclosed in braces. This is a syntax error. • Each catch handler can handle only one type of exception, so each must be declared separately. This is a syntax error. 7. The following code segment should display an error message dialog if the user does not enter two integers: 1 2 3 4 5 6 7 8 9 try { } int number1 = Integer.parseInt( JOptionPane.showInputDialog( "Enter first integer:" ) ); int number2 = Integer.parseInt( JOptionPane.showInputDialog( "Enter second integer:" ) ); JOptionPane.showMessageDialog( this, "The sum is: " + ( number1 + number2 ) ); Your answer: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 try { int number1 = Integer.parseInt( JOptionPane.showInputDialog( "Enter first integer:" ) ); int number2 = Integer.parseInt( JOptionPane.showInputDialog( "Enter second integer:" ) ); JOptionPane.showMessageDialog( this, "The sum is: " + ( number1 + number2 ) ); } catch ( NumberFormatException numberFormatException ) { JOptionPane.showMessageDialog( this, numberFormatException, ); "Exception occurred", JOptionPane.ERROR_MESSAGE ); } 7|Page CPCS 203 Student Name: _____________________________ • • Lab sheet 5 Section: __ A try block must be followed by either a catch handler or a finally block (as a minimum). This is a syntax error. A catch handler must be declared to catch the NumberFormatException and display the error message dialog. Determine if there is an error in each of the following program segments. If there is an error, specify whether it is a logic error or a compilation error, circle the error in the program and write the corrected code in the space provided after each problem. If the code does not contain an error, write “no error.” [Note: There may be more than one error in each program segment.] 8. The following code segment should open a file for object output: ObjectOutputStream output = new ObjectOutputStream( new FileOutput( "file.dat" ) ); 1 2 Your answer: ObjectOutputStream output = new ObjectOutputStream( new FileOutputStream( "file.dat" ) ); 1 2 • FileOutput is not a class in the java.io package. The proper class to use here is FileOutputStream. Compilation error. 9. The following code segment should open a file for object input: FileInputStream input = new FileInputStream( "file.dat" ); 1 Your answer: ObjectInputStream input = new ObjectInputStream( new FileInputStream( "file.dat" ) ); 1 • Although a FileInputStream can be used to read bytes from a file, it does not provide any object input capabilities. This requires the FileInputStream to be wrapped in an ObjectInputStream object, which enables a program to read objects from a stream. Logic error. 8|Page CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: _ 10. The following code segment should write the object named record into a file. Assume that output is a prop- erly defined object of class ObjectOutputStream. output.writeObject( record ); 1 Your answer: output.writeObject( record ); 1 • The proper method name for writing an object is writeObject, not write . Compilation error. 11. The following code segment should open a text file for reading with a Scanner. Scanner input = new Scanner( "myfile.txt" ); 1 Your answer: Scanner input = new Scanner( new File( "myfile.txt" ) ); 1 • To open a file for reading with class the Scanner constructor. Scanner, you must supply a File object as the argument to 12. The following code segment should open a text file for writing with a Formatter. Formatter output = new Formatter(); 1 Your answer: Formatter output = new Formatter( "myfile.txt" ); 1 • To open a text file for writing with class Formatter, you must supply the file name as the argument to the Formatter constructor. This can be done with just the name of the file as a string or by passing an object of class File. 9|Page CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: _ Lab Exercises: Lab Exercise — Access Array The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 11.1–Fig. L 11.3) 5. Problem-Solving Tips 6. Follow-Up Question and Activity The program template represents a complete working Java program with one or more key lines of code replaced with comments. Read the problem description and examine the sample output, then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up question. The source code for the template is available at www.pearsonhighered.com/deitel. Lab Objectives This lab was designed to reinforce programming concepts from Chapter 11 of Java How to Program: 8/e. In this lab, you will practice: • Using exception handling to determine valid inputs. • Using exception handling to write more robust and more fault-tolerant programs. The follow-up question and activity also will give you practice: • Creating your own exception type and throwing exceptions of that type. Description of the Problem Write a program that allows a user to input integer values into a 10-element array and search the array. The program should allow the user to retrieve values from the array by index or by specifying a value to locate. The program should handle any exceptions that might arise when inputting values or accessing array elements. The program should throw a NumberNotFoundException (Fig. L 11.1) if a particular value cannot be found in the array during a search. If an attempt is made to access an element outside the array bounds, catch the ArrayIndexOutOfBoundsException and display an appropriate error message. Also, the program should throw an ArrayIndexOutOfBoundsException if an attempt is made to access an element for which the user has not yet input a value. 10 | P a g e CPCS 203 Student Name: _____________________________ Sample Output Program Template 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // NumberNotFoundException.java public class NumberNotFoundException extends Exception { // no-argument constructor specifies default error message public NumberNotFoundException() { super( "Number not found in array" ); } } // constructor to allow customized error message public NumberNotFoundException( String message ) { super( message ); } // end class NumberNotFoundException Fig. L 5.1 | 1 2 3 4 5 6 NumberNotFoundException.java. // ArrayAccess.java import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; Fig. L 5.2 | 11 | P a g e ArrayAccess.java. (Part 1 of 4.) Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 import import import import javax.swing.JLabel; javax.swing.JOptionPane; javax.swing.JPanel; javax.swing.JTextField; public class ArrayAccess extends JFrame { private JTextField inputField; private JTextField retrieveField1; private JTextField retrieveField2; private JTextField outputField; private JPanel inputArea; private JPanel retrieveArea; private JPanel outputArea; private private private private int num; int index = 0; int array[] = new int[ 10 ]; String result; // set up GUI public ArrayAccess() { super( "Accessing Array values" ); setLayout( new FlowLayout() ); // set up input Panel inputArea = new JPanel(); inputArea.add( new JLabel( "Enter array elements here" ) ); inputField = new JTextField( 10 ); inputArea.add( inputField ); inputField.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { /* Create a try block in which the application reads the number entered in the inputField and assigns it to the next index in the array, then increments instance variable index. */ /* Write catch handlers that catch the two types of exceptions that the previous try block might throw (NumberFormatException and ArrayIndexOutOfBoundsException), and display appropriate messages in error message dialogs. */ inputField.setText( "" ); } // end method actionPerformed } // end anonymous inner class ); // end call to addActionListener // set up retrieve Panel retrieveArea = new JPanel( new GridLayout( 2, 2 ) ); retrieveArea.add( new JLabel( "Enter number to retrieve" ) ); retrieveField1 = new JTextField( 10 ); retrieveArea.add( retrieveField1 ); Fig. L 5.2 | 12 | P a g e ArrayAccess.java. (Part 2 of 4.) Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 Fig. L 5.2 | 13 | P a g e Lab sheet 5 Section: _ retrieveField1.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ) { /* Create a try block in which the application reads from retrieveField1 the number the user wants to find in the array, then searches the current array contents for the number. If the number is found, the outputField should display all the indices in which the number was found. If the number is not found, a NumberNotFoundException should be thrown. */ /* Write catch handlers that the try block might throw NumberNotFoundException), in error message dialogs. catch the two types of exceptions that (NumberFormatException and and display appropriate messages */ retrieveField1.setText( "" ); } // end method actionPerformed } // end anonymous inner class ); // end call to addActionListener retrieveArea.add( new JLabel( "Enter index to retrieve" ) ); retrieveField2 = new JTextField( 10 ); retrieveArea.add( retrieveField2 ); retrieveField2.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ) { /* Create a try block in which the application reads from retrieveField2 the index of a value in the array, then displays the value at that index in the outputField. If the index input by the user is not a number a NumberFormatException should be thrown. If the number input by the user is outside the array bounds or represents an element in which the application has not stored a value, an ArrayIndexOutOfBoundsException should be thrown. */ /* Write catch handlers that catch the two types of exceptions the try block might throw (NumberFormatException and ArrayIndexOutOfBoundsException), and display appropriate messages in error message dialogs. */ retrieveField2.setText( "" ); } // end anonymous inner class } // end new ActionListener ); // end call to addActionListener // set up output Panel outputArea = new JPanel(); outputArea.add( new JLabel( "Result" ) ); outputField = new JTextField( 30 ); outputField.setEditable( false ); outputArea.add( outputField ); ArrayAccess.java. (Part 3 of 4.) CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: _ 118 add( inputArea ); 119 add( retrieveArea ); 120 add( outputArea ); 121 } // end constructor 122 } // end class ArrayAccess Fig. L 11.2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ArrayAccess.java. (Part 4 of 4.) // ArrayAccessTest.java import javax.swing.JFrame; public class ArrayAccessTest { // execute application public static void main( String args[] ) { ArrayAccess application = new ArrayAccess(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); application.setSize( 400, 200 ); application.setVisible( true ); } } // end class ArrayAccessTest Fig. L 5.3 | ArrayAccessTest.java. Problem-Solving Tips 1. When you search the array for a value, you should define a boolean value at the beginning of the try block and initialize it to false. If the value is found in the array, set the boolean value to true. This will help you determine whether you need to throw an exception due to a search key that is not found. 2. Refer to the sample output to decide what messages to display in the error dialogs. 3. Each of the three event handlers will have its own try statement. 4. If you have any questions as you proceed, ask your lab instructor for assistance. Solution [Note: Since only class ArrayAccess was modified, we show only that file here.] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 // ArrayAccess.java import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class ArrayAccess extends JFrame { private JTextField inputField; private JTextField retrieveField1; private JTextField retrieveField2; 14 | P a g e CPCS 203 Student Name: _____________________________ 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 private JTextField outputField; private JPanel inputArea; private JPanel retrieveArea; private JPanel outputArea; private private private private int num; int index = 0; int array[] = new int[ 10 ]; String result; // set up GUI public ArrayAccess() { super( "Accessing Array values" ); setLayout( new FlowLayout() ); 15 | P a g e // set up input Panel inputArea = new JPanel(); inputArea.add( new JLabel( "Enter array elements here" ) ); inputField = new JTextField( 10 ); inputArea.add( inputField ); inputField.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { num = Integer.parseInt( inputField.getText() ); array[ index ] = num; // place value in array index++; } catch ( NumberFormatException formatException ) { JOptionPane.showMessageDialog( null, "Please enter only integer values", "Invalid Input", JOptionPane.ERROR_MESSAGE ); } catch ( ArrayIndexOutOfBoundsException outOfBounds ) { JOptionPane.showMessageDialog( null, "Array may contain only 10 elements", "Array Full", JOptionPane.ERROR_MESSAGE ); } inputField.setText( "" ); } // end method actionPerformed } // end anonymous inner class ); // end call to addActionListener // set up retrieve Panel retrieveArea = new JPanel( new GridLayout( 2, 2 ) ); retrieveArea.add( new JLabel( "Enter number to retrieve" ) ); retrieveField1 = new JTextField( 10 ); retrieveArea.add( retrieveField1 ); retrieveField1.addActionListener( new ActionListener() { Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 Lab sheet 5 Section: _ public void actionPerformed( ActionEvent event ) { try { num = Integer.parseInt( retrieveField1.getText() ); boolean found = false; result = String.format( "%d was in the following fields of the array: ", num ); 16 | P a g e for ( int i = 0; i < index; i++ ) { if ( num == array[ i ] ) { result += String.format( "%d ", i ); found = true; } // end if } // end for if ( found == false ) throw new NumberNotFoundException(); outputField.setText( result ); } // end try catch ( NumberFormatException formatException ) { JOptionPane.showMessageDialog( null, "Please enter only integer values", "Invalid Input", JOptionPane.ERROR_MESSAGE ); } // end catch catch ( NumberNotFoundException numberException ) { JOptionPane.showMessageDialog( null, numberException.getMessage(), "Not Found", JOptionPane.ERROR_MESSAGE ); } // end catch retrieveField1.setText( "" ); } // end method actionPerformed } // end anonymous inner class ); // end call to addActionListener retrieveArea.add( new JLabel( "Enter index to retrieve" ) ); retrieveField2 = new JTextField( 10 ); retrieveArea.add( retrieveField2 ); retrieveField2.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ) { try { num = Integer.parseInt( retrieveField2.getText() ); if ( num >= index || num < 0 ) throw new ArrayIndexOutOfBoundsException( "Index Not Found." ); outputField.setText( String.format( "The number at index %d is %d", num, array[ num ] ) ); } // end try CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: _ 133 catch ( NumberFormatException formatException ) 134 { 135 JOptionPane.showMessageDialog( null, 136 "Array indices must be integer values", 137 "Invalid Input", JOptionPane.ERROR_MESSAGE ); 138 } // end catch 139 catch ( ArrayIndexOutOfBoundsException outOfBounds ) 140 { 141 JOptionPane.showMessageDialog( null, outOfBounds.getMessage(), 142 "Index Out of Bounds", JOptionPane.ERROR_MESSAGE ); 143 } // end catch 144 145 retrieveField2.setText( "" ); 146 } // end anonymous inner class 147 } // end new ActionListener 148 ); // end call to addActionListener 149 150 // set up output Panel 151 outputArea = new JPanel(); 152 outputArea.add( new JLabel( "Result" ) ); 153 outputField = new JTextField( 30 ); 154 outputField.setEditable( false ); 155 outputArea.add( outputField ); 156 157 add( inputArea ); 158 add( retrieveArea ); 159 add( outputArea ); 160 } // end constructor 161 } // end class ArrayAccess Follow-Up Question and Activity 1. Create another exception class called DuplicateValueException that will be thrown if the user inputs a value that already resides in the array. Modify your lab exercise solution to use this new exception class to indicate when a duplicate value is input, in which case an appropriate error message should be displayed. The program should continue normal execution after handling the exception. Solution [Note: We show only the new and modified files here.] 1 2 3 4 5 6 7 8 9 10 11 12 13 // DuplicateValueException.java public class DuplicateValueException extends NumberFormatException { public DuplicateValueException() { super( "Integer can not be a duplicate." ); } } public DuplicateValueException( String message ) { super( message ); } // end class OverflowException 17 | P a g e CPCS 203 Student Name: _____________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 // ArrayAccess.java import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class ArrayAccess extends JFrame { private JTextField inputField; private JTextField retrieveField1; private JTextField retrieveField2; private JTextField outputField; private JPanel inputArea; private JPanel retrieveArea; private JPanel outputArea; private private private private int num; int index = 0; int array[] = new int[ 10 ]; String result; // set up GUI public ArrayAccess() { super( "Accessing Array values" ); setLayout( new FlowLayout() ); 18 | P a g e // set up input Panel inputArea = new JPanel(); inputArea.add( new JLabel( "Enter array elements here" ) ); inputField = new JTextField( 10 ); inputArea.add( inputField ); inputField.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { num = Integer.parseInt( inputField.getText() ); // determine whether num is a duplicate for ( int i = 0; i < index; i++ ) { if ( num == array[ i ] ) throw new DuplicateValueException(); } // end for array[ index ] = num; // place value in array index++; } catch ( DuplicateValueException duplicateValueException ) { Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 JOptionPane.showMessageDialog( null, "Please enter only unique integers", "Duplicate Value", JOptionPane.ERROR_MESSAGE ); } catch ( NumberFormatException formatException ) { JOptionPane.showMessageDialog( null, "Please enter only integer values", "Invalid Input", JOptionPane.ERROR_MESSAGE ); } catch ( ArrayIndexOutOfBoundsException outOfBounds ) { JOptionPane.showMessageDialog( null, "Array may contain only 10 elements", "Array Full", JOptionPane.ERROR_MESSAGE ); } 19 | P a g e inputField.setText( "" ); } // end method actionPerformed } // end anonymous inner class ); // end call to addActionListener // set up retrieve Panel retrieveArea = new JPanel( new GridLayout( 2, 2 ) ); retrieveArea.add( new JLabel( "Enter number to retrieve" ) ); retrieveField1 = new JTextField( 10 ); retrieveArea.add( retrieveField1 ); retrieveField1.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ) { try { num = Integer.parseInt( retrieveField1.getText() ); boolean found = false; result = String.format( "%d was in the following fields of the array: ", num ); for ( int i = 0; i < index; i++ ) { if ( num == array[ i ] ) { result += String.format( "%d ", i ); found = true; } // end if } // end for if ( found == false ) throw new NumberNotFoundException(); outputField.setText( result ); } // end try catch ( NumberFormatException formatException ) { JOptionPane.showMessageDialog( null, "Please enter only integer values", "Invalid Input", JOptionPane.ERROR_MESSAGE ); } // end catch Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: _ 118 catch ( NumberNotFoundException numberException ) 119 { 120 JOptionPane.showMessageDialog( null, numberException.getMessage(), 121 "Not Found", JOptionPane.ERROR_MESSAGE ); 122 } // end catch 123 124 retrieveField1.setText( "" ); 125 } // end method actionPerformed 126 } // end anonymous inner class 127 ); // end call to addActionListener 128 129 retrieveArea.add( new JLabel( "Enter index to retrieve" ) ); 130 retrieveField2 = new JTextField( 10 ); 131 retrieveArea.add( retrieveField2 ); 132 retrieveField2.addActionListener( 133 new ActionListener() 134 { 135 public void actionPerformed( ActionEvent event ) 136 { 137 try 138 { 139 num = Integer.parseInt( retrieveField2.getText() ); 140 141 if ( num >= index || num < 0 ) 142 throw new ArrayIndexOutOfBoundsException( "Index Not Found." ); 143 144 outputField.setText( String.format( 145 "The number at index %d is %d", num, array[ num ] ) ); 146 } // end try 147 catch ( NumberFormatException formatException ) 148 { 149 JOptionPane.showMessageDialog( null, 150 "Array indices must be integer values", 151 "Invalid Input", JOptionPane.ERROR_MESSAGE ); 152 } // end catch 153 catch ( ArrayIndexOutOfBoundsException outOfBounds ) 154 { 155 JOptionPane.showMessageDialog( null, outOfBounds.getMessage(), 156 "Index Out of Bounds", JOptionPane.ERROR_MESSAGE ); 157 } // end catch 158 159 retrieveField2.setText( "" ); 160 } // end anonymous inner class 161 } // end new ActionListener 162 ); // end call to addActionListener 163 164 // set up output Panel 165 outputArea = new JPanel(); 166 outputArea.add( new JLabel( "Result" ) ); 167 outputField = new JTextField( 30 ); 168 outputField.setEditable( false ); 169 outputArea.add( outputField ); 170 171 add( inputArea ); 172 add( retrieveArea ); 173 add( outputArea ); 174 } // end constructor 175 } // end class ArrayAccess 20 | P a g e CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: _ Lab Exercises: Lab Exercise 2 — Employee Hierarchy with Object Serialization This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 5.4–Fig. L 5.5) 5. Problem-Solving Tips 6. Follow-Up Questions and Activities The program template represents a complete working Java program with one or more key lines of code replaced with comments. Read the problem description and examine the sample output; then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. The source code for the template is available at www.pearsonhighered.com/deitel. Lab Objectives This lab was designed to reinforce programming concepts from Chapter 17 of Java How to Program: 8/e. In this lab you will practice: • • Modifying a class hierarchy to ensure that objects of the classes in the hierarchy are Serializable. Opening a file for output. • Writing objects to a file. The follow-up questions and activities will also give you practice: • Opening a file for input. • Reading objects to a file. • Reading and writing entire arrays of Serializable objects. Problem Description Modify the Employee hierarchy from Figs. 10.4–10.8 to enable serialization of the classes in the hierarchy. Then, modify the application of Fig. 10.9 to output each object in the array employees to a file using object serialization. [Note: In the follow-up questions, you will be asked to read these objects from the file created here.] 21 | P a g e CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: _ Sample Output Employees processed individually: salaried employee: John Smith social security number: 111-11-1111 weekly salary: $800.00 earned: $800.00 hourly employee: Karen Price social security number: 222-22-2222 hourly wage: $16.75; hours worked: 40.00 earned: $670.00 commission employee: Sue Jones social security number: 333-33-3333 gross sales: $10,000.00; commission rate: 0.06 earned: $600.00 base-salaried commission employee: Bob Lewis social security number: 444-44-4444 gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00 earned: $500.00 Template 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // Lab Exercise 1: Employee.java // Employee abstract superclass. /* import the Serializable interface */ /* modify the following class to make all objects of its subclasses Serializable */ public abstract class Employee { private String firstName; private String lastName; private String socialSecurityNumber; // three-argument constructor public Employee( String first, String last, String ssn ) { firstName = first; lastName = last; socialSecurityNumber = ssn; } // end three-argument Employee constructor // set first name public void setFirstName( String first ) { firstName = first; } // end method setFirstName // return first name public String getFirstName() { return firstName; } // end method getFirstName Fig. L 5.4 | 22 | P a g e Employee abstract superclass. (Part 1 of 2.) CPCS 203 Student Name: _____________________________ 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 // set last name public void setLastName( String last ) { lastName = last; } // end method setLastName // return last name public String getLastName() { return lastName; } // end method getLastName // set social security number public void setSocialSecurityNumber( String ssn ) { socialSecurityNumber = ssn; // should validate } // end method setSocialSecurityNumber // return social security number public String getSocialSecurityNumber() { return socialSecurityNumber; } // end method getSocialSecurityNumber // return String representation of Employee object public String toString() { return String.format( "%s %s\nsocial security number: %s", getFirstName(), getLastName(), getSocialSecurityNumber() ); } // end method toString // abstract method overridden by subclasses public abstract double earnings(); // no implementation here } // end abstract class Employee Fig. L 5.4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Lab sheet 5 Section: _ Employee abstract superclass. (Part 2 of 2.) // Lab Exercise 1: OutputEmployees.java // Employee hierarchy test program. /* import the java.io package classes necessary for writing objects into a file */ public class OutputEmployees { public static void main( String args[] ) { // create subclass objects SalariedEmployee salariedEmployee = new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 ); HourlyEmployee hourlyEmployee = new HourlyEmployee( "Karen", "Price", "222-22-2222", 16.75, 40 ); CommissionEmployee commissionEmployee = new CommissionEmployee( "Sue", "Jones", "333-33-3333", 10000, .06 ); Fig. L 17.2 | 23 | P a g e Employee class hierarchy test program. (Part 1 of 2.) CPCS 203 Student Name: _____________________________ 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 Lab sheet 5 Section: _ BasePlusCommissionEmployee basePlusCommissionEmployee = new BasePlusCommissionEmployee( "Bob", "Lewis", "444-44-4444", 5000, .04, 300 ); System.out.println( "Employees processed individually:\n" ); System.out.printf( "%s\n%s: $%,.2f\n\n", salariedEmployee, "earned", salariedEmployee.earnings() ); System.out.printf( "%s\n%s: $%,.2f\n\n", hourlyEmployee, "earned", hourlyEmployee.earnings() ); System.out.printf( "%s\n%s: $%,.2f\n\n", commissionEmployee, "earned", commissionEmployee.earnings() ); System.out.printf( "%s\n%s: $%,.2f\n\n", basePlusCommissionEmployee, "earned", basePlusCommissionEmployee.earnings() ); // create four-element Employee array Employee employees[] = new Employee[ 4 ]; // initialize employees[ 0 employees[ 1 employees[ 2 employees[ 3 ] ] ] ] array with Employees = salariedEmployee; = hourlyEmployee; = commissionEmployee; = basePlusCommissionEmployee; System.out.println( "Output the elements of the array:\n" ); /* Write code here that opens the file EmployeeData.ser for object output then writes all the elements of the array employees into the file */ } // end main } // end class OutputEmployees Fig. L 5.5 | Employee class hierarchy test program. (Part 2 of 2.) Problem-Solving Tips 1. To write objects with an ObjectOutputStream, the objects’ class(es) must implement interface Serializable . You can do this for all objects in the Employee hierarchy by simply implementing the Serializable interface in the superclass Employee. Then, the Serializable relationship is inherited into all of class Employee’s subclasses. 2. Code related to processing object streams might throw exceptions for many reasons. All IOExceptions are checked exceptions, so these exceptions must be caught or your program will not compile. 3. If you have any questions as you proceed, ask your lab instructor for assistance. Solution 1 2 3 4 5 6 7 8 9 // Fig. 10.4: Employee.java // Employee abstract superclass. import java.io.Serializable; public abstract class Employee implements Serializable { private String firstName; private String lastName; private String socialSecurityNumber; 24 | P a g e CPCS 203 Student Name: _____________________________ 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 // three-argument constructor public Employee( String first, String last, String ssn ) { firstName = first; lastName = last; socialSecurityNumber = ssn; } // end three-argument Employee constructor // set first name public void setFirstName( String first ) { firstName = first; } // end method setFirstName // return first name public String getFirstName() { return firstName; } // end method getFirstName // set last name public void setLastName( String last ) { lastName = last; } // end method setLastName // return last name public String getLastName() { return lastName; } // end method getLastName // set social security number public void setSocialSecurityNumber( String ssn ) { socialSecurityNumber = ssn; // should validate } // end method setSocialSecurityNumber // return social security number public String getSocialSecurityNumber() { return socialSecurityNumber; } // end method getSocialSecurityNumber // return String representation of Employee object public String toString() { return String.format( "%s %s\nsocial security number: %s", getFirstName(), getLastName(), getSocialSecurityNumber() ); } // end method toString // abstract method overridden by subclasses public abstract double earnings(); // no implementation here } // end abstract class Employee 25 | P a g e Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 // Lab Exercise 1: OutputEmployees.java // Employee hierarchy test program. import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.io.IOException; public class OutputEmployees { public static void main( String args[] ) { // create subclass objects SalariedEmployee salariedEmployee = new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 ); HourlyEmployee hourlyEmployee = new HourlyEmployee( "Karen", "Price", "222-22-2222", 16.75, 40 ); CommissionEmployee commissionEmployee = new CommissionEmployee( "Sue", "Jones", "333-33-3333", 10000, .06 ); BasePlusCommissionEmployee basePlusCommissionEmployee = new BasePlusCommissionEmployee( "Bob", "Lewis", "444-44-4444", 5000, .04, 300 ); System.out.println( "Employees processed individually:\n" ); System.out.printf( "%s\n%s: $%,.2f\n\n", salariedEmployee, "earned", salariedEmployee.earnings() ); System.out.printf( "%s\n%s: $%,.2f\n\n", hourlyEmployee, "earned", hourlyEmployee.earnings() ); System.out.printf( "%s\n%s: $%,.2f\n\n", commissionEmployee, "earned", commissionEmployee.earnings() ); System.out.printf( "%s\n%s: $%,.2f\n\n", basePlusCommissionEmployee, "earned", basePlusCommissionEmployee.earnings() ); // create four-element Employee array Employee employees[] = new Employee[ 4 ]; // initialize employees[ 0 employees[ 1 employees[ 2 employees[ 3 try { ] ] ] ] array with Employees = salariedEmployee; = hourlyEmployee; = commissionEmployee; = basePlusCommissionEmployee; ObjectOutputStream output = new ObjectOutputStream( new FileOutputStream( "EmployeeData.ser" ) ); for ( Employee currentEmployee : employees ) output.writeObject( currentEmployee ); } catch ( IOException exception ) { exception.printStackTrace(); } } // end main } // end class OutputEmployees 26 | P a g e Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: _ Follow-Up Questions and Activities 1. Modify the application of Fig. 10.9 to read the objects in the file EmployeeData.ser into an array called employees, then output the contents of the array polymorphically as in Fig. 10.9. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 // Lab Exercise 1, Follow-Up 1: InputEmployees.java // Employee hierarchy test program. import java.io.FileInputStream; import java.io.ObjectInputStream; import java.io.IOException; import java.lang.ClassNotFoundException; public class InputEmployees { public static void main( String args[] ) { // create four-element Employee array Employee employees[] = new Employee[ 4 ]; 27 | P a g e try { ObjectInputStream input = new ObjectInputStream( new FileInputStream( "EmployeeData.ser" ) ); for ( int i = 0; i < employees.length; i++ ) employees[ i ] = ( Employee ) input.readObject(); } catch ( ClassNotFoundException cnfException ) { cnfException.printStackTrace(); } catch ( IOException ioException ) { ioException.printStackTrace(); } System.out.println( "Employees processed polymorphically:\n" ); // generically process each element in array employees for ( Employee currentEmployee : employees ) { System.out.println( currentEmployee ); // invokes toString // determine whether element is a BasePlusCommissionEmployee if ( currentEmployee instanceof BasePlusCommissionEmployee ) { // downcast Employee reference to // BasePlusCommissionEmployee reference BasePlusCommissionEmployee employee = ( BasePlusCommissionEmployee ) currentEmployee; double oldBaseSalary = employee.getBaseSalary(); employee.setBaseSalary( 1.10 * oldBaseSalary ); System.out.printf( "new base salary with 10%% increase is: $%,.2f\n", employee.getBaseSalary() ); } // end if CPCS 203 Student Name: _____________________________ 54 55 56 57 58 59 60 61 62 63 Lab sheet 5 Section: _ System.out.printf( "earned $%,.2f\n\n", currentEmployee.earnings() ); } // end for // get type name of each object in employees array for ( int j = 0; j < employees.length; j++ ) System.out.printf( "Employee %d is a %s\n", j, employees[ j ].getClass().getName() ); } // end main } // end class InputEmployees Employees processed polymorphically: salaried employee: John Smith social security number: 111-11-1111 weekly salary: $800.00 earned $800.00 hourly social hourly earned employee: Karen Price security number: 222-22-2222 wage: $16.75; hours worked: 40.00 $670.00 commission employee: Sue Jones social security number: 333-33-3333 gross sales: $10,000.00; commission rate: 0.06 earned $600.00 base-salaried commission employee: Bob Lewis social security number: 444-44-4444 gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00 new base salary with 10% increase is: $330.00 earned $530.00 Employee Employee Employee Employee 0 1 2 3 is is is is a a a a SalariedEmployee HourlyEmployee CommissionEmployee BasePlusCommissionEmployee 2. Since arrays are objects in Java, entire arrays of Serializable objects can be output simply by passing an array’s name to an ObjectOutputStream’s writeObject method. Similarly, an entire array of Serializable objects can be read with a single call to an ObjectInputStream’s readObject method. Modify class OutputEmployees from Lab Exercise 1 to write the entire array to the file with a single output statement. Then, modify class InputEmployees from Follow-Up Exercise 1 to read the entire array with a single statement. 1 2 3 4 5 6 7 8 9 // Lab Exercise 1, Follow-Up 2: OutputEmployees.java // Employee hierarchy test program. import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.io.IOException; public class OutputEmployees { public static void main( String args[] ) 28 | P a g e CPCS 203 Student Name: _____________________________ 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 1 2 3 4 5 6 7 8 9 Lab sheet 5 Section: _ // create subclass objects SalariedEmployee salariedEmployee = new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 ); HourlyEmployee hourlyEmployee = new HourlyEmployee( "Karen", "Price", "222-22-2222", 16.75, 40 ); CommissionEmployee commissionEmployee = new CommissionEmployee( "Sue", "Jones", "333-33-3333", 10000, .06 ); BasePlusCommissionEmployee basePlusCommissionEmployee = new BasePlusCommissionEmployee( "Bob", "Lewis", "444-44-4444", 5000, .04, 300 ); System.out.println( "Employees processed individually:\n" ); System.out.printf( "%s\n%s: $%,.2f\n\n", salariedEmployee, "earned", salariedEmployee.earnings() ); System.out.printf( "%s\n%s: $%,.2f\n\n", hourlyEmployee, "earned", hourlyEmployee.earnings() ); System.out.printf( "%s\n%s: $%,.2f\n\n", commissionEmployee, "earned", commissionEmployee.earnings() ); System.out.printf( "%s\n%s: $%,.2f\n\n", basePlusCommissionEmployee, "earned", basePlusCommissionEmployee.earnings() ); // create four-element Employee array Employee employees[] = new Employee[ 4 ]; // initialize employees[ 0 employees[ 1 employees[ 2 employees[ 3 try { ] ] ] ] array with Employees = salariedEmployee; = hourlyEmployee; = commissionEmployee; = basePlusCommissionEmployee; ObjectOutputStream output = new ObjectOutputStream( new FileOutputStream( "EmployeeData.ser" ) ); output.writeObject( employees ); } catch ( IOException exception ) { exception.printStackTrace(); } } // end main } // end class OutputEmployees // Lab Exercise 1, Follow-Up 2: InputEmployees.java // Employee hierarchy test program. import java.io.FileInputStream; import java.io.ObjectInputStream; import java.io.IOException; import java.lang.ClassNotFoundException; public class InputEmployees { 29 | P a g e CPCS 203 Student Name: _____________________________ 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 public static void main( String args[] ) { // create four-element Employee array Employee employees[] = new Employee[ 4 ]; try { ObjectInputStream input = new ObjectInputStream( new FileInputStream( "EmployeeData.ser" ) ); employees = ( Employee[] ) input.readObject(); } catch ( ClassNotFoundException cnfException ) { cnfException.printStackTrace(); } catch ( IOException ioException ) { ioException.printStackTrace(); } System.out.println( "Employees processed polymorphically:\n" ); // generically process each element in array employees for ( Employee currentEmployee : employees ) { System.out.println( currentEmployee ); // invokes toString // determine whether element is a BasePlusCommissionEmployee if ( currentEmployee instanceof BasePlusCommissionEmployee ) { // downcast Employee reference to // BasePlusCommissionEmployee reference BasePlusCommissionEmployee employee = ( BasePlusCommissionEmployee ) currentEmployee; double oldBaseSalary = employee.getBaseSalary(); employee.setBaseSalary( 1.10 * oldBaseSalary ); System.out.printf( "new base salary with 10%% increase is: $%,.2f\n", employee.getBaseSalary() ); } // end if System.out.printf( "earned $%,.2f\n\n", currentEmployee.earnings() ); } // end for // get type name of each object in employees array for ( int j = 0; j < employees.length; j++ ) System.out.printf( "Employee %d is a %s\n", j, employees[ j ].getClass().getName() ); } // end main } // end class InputEmployees 30 | P a g e Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ Employees processed polymorphically: salaried employee: John Smith social security number: 111-11-1111 weekly salary: $800.00 earned $800.00 hourly social hourly earned employee: Karen Price security number: 222-22-2222 wage: $16.75; hours worked: 40.00 $670.00 commission employee: Sue Jones social security number: 333-33-3333 gross sales: $10,000.00; commission rate: 0.06 earned $600.00 base-salaried commission employee: Bob Lewis social security number: 444-44-4444 gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00 new base salary with 10% increase is: $330.00 earned $530.00 Employee Employee Employee Employee 31 | P a g e 0 1 2 3 is is is is a a a a SalariedEmployee HourlyEmployee CommissionEmployee BasePlusCommissionEmployee Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: _ Lab Exercises: Lab Exercise 3 — Debugging The program in this section does not compile. Fix all the syntax errors, so that the program will compile success- fully. Once the program compiles, execute the program, and compare the output with the sample output. Then eliminate any logic errors that may exist. The sample output demonstrates what the program’s output should be once the program’s code is corrected. The source code is available at the Web sites www.pearsonhighered.com/ deitel. Sample Output SpecialIOException: Special IO Exception Occurred Broken Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 import java.io.IOException; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // Debugging Chapter 11: DebugException.java import java.io.IOException; public class SpecialIOException throws IOException { public SpecialIOException() { super( "Special IO Exception Occurred" ); } } public SpecialIOException( String message ) { this( message ); } // end class SpecialIOException public class DebugException { public static void main( String args[] ) { try { throw new SpecialIOException(); } catch ( Exception exception ) { System.err.println( exception.toString() ); } catch ( IOException ioException ) { System.err.println( ioException.toString() ); } 32 | P a g e CPCS 203 Student Name: _____________________________ 20 21 22 23 24 25 } Lab sheet 5 Section: _ catch ( SpecialIOException specialIOException ) { specialIOException.toString(); } } // end method main // end class DebugException Solution 1 2 3 4 5 6 7 8 9 10 11 12 13 14 import java.io.IOException; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Debugging solution Chapter 14: DebugException.java import java.io.IOException; public class SpecialIOException extends IOException { public SpecialIOException() { super( "Special IO Exception Occurred" ); } } public SpecialIOException(String message) { super( message ); } // end class SpecialIOException public class DebugException { public static void main( String args[] ) { try { throw new SpecialIOException(); } catch ( SpecialIOException specialIOException ) { System.err.println( specialIoException.toString() ); } catch ( IOException ioException ) { System.err.println( ioException.toString() ); } catch ( Exception exception ) { System.err.println( exception.toString() ); } } // end method main } // end class DebugException List of Errors: • The keyword throws should be replaced with extends in the first line of class Compilation error. 33 | P a g e SpecialIOException. CPCS 203 Student Name: _____________________________ • • • Lab sheet 5 Section: _ The second constructor of class SpecialIOException calls itself recursively. It should call the superclass constructor by using the keyword super rather than the keyword this. Compilation error. In class DebugException the exception handlers following the try block should be listed in subclass to superclass order (i.e., SpecialIOException, IOException and Exception). Compilation error. The SpecialIOException catch handler does not actually output an error message. Place the call to toString in a System.err.println statement to output the information to the user. Logic error. 34 | P a g e CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: _ Postlab Activities Coding Exercises These coding exercises reinforce the lessons learned in the lab and provide additional programming experience outside the classroom and laboratory environment. They serve as a review after you have successfully completed the Prelab Activities and Lab Exercises. For each of the following problems, write a program or a program segment that performs the specified action: 1. Define a class InvalidInputException. This class should be a direct subclass of Exception. It should specify the default message "Your input was invalid.", but should also enable the programmer to specify a custom message as well. 1 2 3 4 5 6 7 8 9 10 11 12 13 // Coding Exercise 1: InvalidInputException.java public class InvalidInputException extends Exception { public InvalidInputException() { super( "Your input was invalid" ); } } public InvalidInputException( String message ) { super( message ); } // end class InvalidInputException 2. Define a class ExceptionTest based on class DivideByZeroWithExceptionHandling of Fig. 11.2 of Java How To Program: 8/e. Not only should ExceptionTest check for division by zero and valid integer input, it should also ensure that the integers being input are positive. If they are not, it should throw an InvalidInputException (using the class from Coding Exercise 1) with the message "You must enter positive numbers". The program should catch this exception and display an error message. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 // Coding Exercise 2: ExceptionTest.java // An exception-handling example that checks for divide-by-zero. import java.util.InputMismatchException; import java.util.Scanner; public class ExceptionTest { // demonstrates throwing an exception when a divide-by-zero occurs public static int quotient( int numerator, int denominator ) throws ArithmeticException { return numerator / denominator; // possible division by zero } // end method quotient 35 | P a g e CPCS 203 Student Name: _____________________________ 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 Lab sheet 5 Section: _ public static void main( String args[] ) { Scanner scanner = new Scanner( System.in ); // scanner for input boolean continueLoop = true; // determines if more input is needed do { try // read two numbers and calculate quotient { System.out.print( "Please enter an integer numerator: " ); int numerator = scanner.nextInt(); System.out.print( "Please enter an integer denominator: " ); int denominator = scanner.nextInt(); if ( ( numerator < 0 ) || ( denominator < 0 ) ) throw new InvalidInputException( "You must enter positive numbers" ); int result = quotient( numerator, denominator ); System.out.printf( "\nResult: %d / %d = %d\n", numerator, denominator, result ); continueLoop = false; // input successful; end looping } // end try catch ( InvalidInputException invalidInputException ) { System.err.println( invalidInputException ); System.out.println( "Please try again.\n" ); } catch ( InputMismatchException inputMismatchException ) { System.err.println( inputMismatchException ); scanner.nextLine(); // discard input so user can try again System.out.println( "You must enter integers. Please try again.\n" ); } // end catch catch ( ArithmeticException arithmeticException ) { System.err.println( arithmeticException ); System.out.println( "Zero is an invalid denominator. Please try again.\n" ); } // end catch } while ( continueLoop ); // end do...while } // end main } // end class ExceptionTest 36 | P a g e CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: _ These coding exercises reinforce the lessons learned in the lab and provide additional programming experience outside the classroom and laboratory environment. They serve as a review after you have successfully completed the Prelab Activities and Lab Exercises. For each of the following problems, write a program or a program that performs the specified action(s). 3. Create a simple sequential-access file-processing program that might be used by professors to help manage their student records. For each student, the program should obtain an ID number, the student’s first name, the student’s last name and the student’s grade. The data obtained for each student constitutes a record for the student and should be stored in an object of a class called Student. The program should save the records in a file specified by the user. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 // Coding Exercise 1: Student.java // A class that represents one record of student information. public class Student { private int studentID; private String firstName; private String lastName; private double grade; // no-argument constructor calls other constructor with default values public Student() { this( 0, "", "", 0.0 ); // call four-argument constructor } // end no-argument Student constructor // initialize a record public Student( int id, String first, String last, double grade ) { setStudentID( id ); setFirstName( first ); setLastName( last ); setGrade( grade ); } // end four-argument Student constructor // set student ID number public void setStudentID( int id ) { studentID = id; } // end method setStudentID // get student ID number public int getStudentID() { return studentID; } // end method getStudentID 37 | P a g e CPCS 203 Student Name: _____________________________ 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // set first name public void setFirstName( String first ) { firstName = first; } // end method setFirstName // get first name public String getFirstName() { return firstName; } // end method getFirstName // set last name public void setLastName( String last ) { lastName = last; } // end method setLastName // get last name public String getLastName() { return lastName; } // end method getLastName // set grade public void setGrade( double gradeValue ) { grade = gradeValue; } // end method setGrade // get grade public double getGrade() { return grade; } // end method getGrade } // end class Student // Coding Exercise 1: CreateTextFile.java // Writing data to a text file with class Formatter. import java.io.FileNotFoundException; import java.lang.SecurityException; import java.util.Formatter; import java.util.FormatterClosedException; import java.util.NoSuchElementException; import java.util.Scanner; public class CreateTextFile { private Formatter output; // used to output text to file private Scanner input; // used to input text from the instructor // enable user to open file public void openFile() { try { 38 | P a g e Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 input = new Scanner( System.in ); System.out.println( "Enter the name of the file in which to store student records:" ); // read the file name and use it to create a Formatter object output = new Formatter( input.nextLine() ); } // end try catch ( SecurityException securityException ) { System.err.println( "You do not have write access to this file." ); System.exit( 1 ); } // end catch catch ( FileNotFoundException filesNotFoundException ) { System.err.println( "Error creating file." ); System.exit( 1 ); } // end catch } // end method openFile // add records to file public void addRecords() { // object to be written to file Student record = new Student(); 39 | P a g e System.out.printf( "%s\n%s\n%s\n%s\n\n", "To terminate input, type the end-of-file indicator ", "when you are prompted to enter input.", "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter", "On Windows type <ctrl> z then press Enter" ); System.out.printf( "%s\n? ", "Enter student ID number (> 0), first name, last name and grade:" ); while ( input.hasNext() ) // loop until end-of-file indicator { try // output values to file { // retrieve data to be output record.setStudentID( input.nextInt() ); // read student ID number record.setFirstName( input.next() ); // read first name record.setLastName( input.next() ); // read last name record.setGrade( input.nextDouble() ); // read grade if ( record.getStudentID() > 0 ) { // write new record output.format( "%d %s %s %.2f\n", record.getStudentID(), record.getFirstName(), record.getLastName(), record.getGrade() ); } // end if else { System.out.println( "Student ID number must be greater than 0." ); } // end else } // end try Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ 78 catch ( FormatterClosedException formatterClosedException ) 79 { 80 System.err.println( "Error writing to file." ); 81 return; 82 } // end catch 83 catch ( NoSuchElementException elementException ) 84 { 85 System.err.println( "Invalid input. Please try again." ); 86 input.nextLine(); // discard input so user can try again 87 } // end catch 88 89 System.out.printf( "%s\n? ", 90 "Enter student ID number (> 0), first name, last name and grade:" ); 91 } // end while 92 } // end method addRecords 93 94 // close file 95 public void closeFile() 96 { 97 if ( output != null ) 98 output.close(); 99 } // end method closeFile 100 } // end class CreateTextFile 1 2 3 4 5 6 7 8 9 10 11 12 13 14 // Coding Exercise 1: CreateTextFileTest.java // Testing the CreateTextFile class. public class CreateTextFileTest { public static void main( String args[] ) { CreateTextFile application = new CreateTextFile(); application.openFile(); application.addRecords(); application.closeFile(); } // end main } // end class CreateTextFileTest Enter the name of the file in which to store student records: students.txt To terminate input, type the end-of-file indicator when you are prompted to enter input. On UNIX/Linux/Mac OS X type <ctrl> d then press Enter On Windows type <ctrl> z then press Enter Enter student ID number ? 1 Suzy Green 88.6 Enter student ID number ? 2 Jessica Purple 98.3 Enter student ID number ? 3 Paul Orange 75.9 Enter student ID number ? ^Z 40 | P a g e (> 0), first name, last name and grade: (> 0), first name, last name and grade: (> 0), first name, last name and grade: (> 0), first name, last name and grade: Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: _ 4. Create a simple sequential-access file-processing program to complement the program in Coding Exercise 1. This program should open the file created by the Coding Exercise 1 program and read and display the grade information for each student. The program should also display the class average. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 // Coding Exercise 2: ReadTextFile.java // This program reads a text file and displays each record and // displays the class average. import java.io.File; import java.io.FileNotFoundException; import java.lang.IllegalStateException; import java.util.NoSuchElementException; import java.util.Scanner; public class ReadTextFile { private Scanner input; // enable user to open file public void openFile() { try { Scanner tempScanner = new Scanner( System.in ); System.out.println( "Enter the name of the file containing the student records:" ); String fileName = tempScanner.nextLine(); input = new Scanner( new File( fileName ) ); } // end try catch ( FileNotFoundException fileNotFoundException ) { System.err.println( "Error opening file." ); System.exit( 1 ); } // end catch } // end method openFile // read record from file public void readRecords() { // object to be written to screen Student record = new Student(); 41 | P a g e double total = 0; // stores total of all grades int gradeCounter = 0; // counts grades input System.out.printf( "\n%-12s%-12s%-12s%10s\n", "Student ID", "First Name", "Last Name", "Grade" ); try // read records from file using Scanner object { while ( input.hasNext() ) { record.setStudentID( input.nextInt() ); // read account number record.setFirstName( input.next() ); // read first name record.setLastName( input.next() ); // read last name record.setGrade( input.nextDouble() ); // read balance CPCS 203 Student Name: _____________________________ 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 1 2 3 4 5 6 7 8 9 10 11 12 13 14 // display record contents System.out.printf( "%-12d%-12s%-12s%10.2f\n", record.getStudentID(), record.getFirstName(), record.getLastName(), record.getGrade() ); ++gradeCounter; total += record.getGrade(); } // end while System.out.printf( "\nClass average is: %.2f\n", ( total / gradeCounter ) ); } // end try catch ( NoSuchElementException elementException ) { System.err.println( "File improperly formed." ); input.close(); System.exit( 1 ); } // end catch catch ( IllegalStateException stateException ) { System.err.println( "Error reading from file." ); System.exit( 1 ); } // end catch } // end method readRecords // close file and terminate application public void closeFile() { if ( input != null ) input.close(); // close file } // end method closeFile } // end class ReadTextFile // Coding Exercise 2: ReadTextFileTest.java // This program test class ReadTextFile. public class ReadTextFileTest { public static void main( String args[] ) { ReadTextFile application = new ReadTextFile(); application.openFile(); application.readRecords(); application.closeFile(); } // end main } // end class ReadTextFileTest 42 | P a g e Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ Enter the name of the file containing the student records: students.txt Student ID 1 2 3 First Name Suzy Jessica Paul Class average is: 87.60 43 | P a g e Last Name Green Purple Orange Grade 88.60 98.30 75.90 Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: _ Postlab Activities Name: Programming Challenges The Programming Challenges are more involved than the Coding Exercises and may require a significant amount of time to complete. Write a Java program for each of the problems in this section. The answers to these problems are available at www.pearsonhighered.com/deitel. Pseudocode, hints or sample outputs are provided for each problem to aid you in your programming. 5. (Telephone-Number Word Generator) Standard telephone keypads contain the digits zero through nine. The numbers two through nine each have three letters associated with them. (See Fig. L 5.3.) Many people find it difficult to memorize phone numbers, so they use the correspondence between digits and letters to develop seven-letter words that correspond to their phone numbers. For example, a person whose telephone number is 686-2377 might use the correspondence indicated in Fig. L 5.3 to develop the seven-letter word “NUMBERS.” Each seven-letter word corresponds to exactly one seven-digit telephone number. The restaurant wishing to increase its takeout business could surely do so with the number 825-3688 (i.e., “TAKEOUT”). Each seven-letter phone number corresponds to many separate seven-letter words. Unfortunately, most of these words represent unrecognizable juxtapositions of letters. It is possible, however, that the owner of a barbershop would be pleased to know that the shop’s telephone number, 424-7288, corresponds to “HAIRCUT.” The owner of a liquor store would, no doubt, be delighted to find that the store’s number, 2337226, corresponds to “BEERCAN.” A veterinarian with the phone number 738-2273 would be pleased to know that the number corresponds to the letters “PETCARE.” An automotive dealership would be pleased to know that the dealership number, 639-2277, corresponds to “NEWCARS.” Write a program that, given a seven-digit number, uses a Formatter object to write to a file every possible seven-letter word combination corresponding to that number. There are 2187 (37) such combinations. Avoid phone numbers with the digits 0 and 1. Digit Letters 2 A B C 3 D E F 4 G H I 5 J K L 6 M N O 7 P R S 8 T U V 9 W X Y Fig. L 5.3 | Telephone keypad digits and letters. 44 | P a g e CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: _ Solution 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 // Programming Challenge 1 Solution: Phone.java // Note: phone number must be input in the form #######. // Only the digits 2 through 9 are recognized. import java.io.File; import java.io.FileNotFoundException; import java.util.Formatter; import java.util.FormatterClosedException; import java.util.IllegalFormatException; public class Phone { private int phoneNumber[]; // output letter combinations to file public void calculate( int phoneNumber ) { String letters[][] = { { " ", " ", " " }, { " ", " ", " " }, { "A", "B", "C" }, { "D", "E", "F" }, { "G", "H", "I" }, { "J", "K", "L" }, { "M", "N", "O" }, { "P", "R", "S" }, { "T", "U", "V" }, { "W", "X", "Y" } }; 45 | P a g e int digits[] = new int[ 7 ]; for ( int i = 6; i >= 0; i-- ) { digits[ i ] = ( int )( phoneNumber % 10 ); phoneNumber /= 10; } // end for Formatter output = null; try { output = new Formatter( "phone.txt" ); } // end try catch ( SecurityException securityException ) { System.out.println( "You do not have write access to this file." ); System.exit( 1 ); } // end catch catch ( FileNotFoundException fileNotFoundException ) { System.out.println( "Error creating file." ); System.exit( 1 ); } // end catch System.out.println( "Please wait..." ); try { int int int int int loop1; // loop2; // loop3; // loop4; // loop5; // loop loop loop loop loop counter counter counter counter counter for for for for for first digit of phone number second digit of phone number third digit of phone number fourth digit of phone number fifth digit of phone number CPCS 203 Student Name: _____________________________ 57 int loop6; // loop counter for sixth digit of phone number 58 int loop7; // loop counter for seventh digit of phone number 59 60 // output all possible combinations 61 for ( loop1 = 0; loop1 <= 2; loop1++ ) 62 { 63 for ( loop2 = 0; loop2 <= 2; loop2++ ) 64 { 65 for ( loop3 = 0; loop3 <= 2; loop3++ ) 66 { 67 for ( loop4 = 0; loop4 <= 2; loop4++ ) 68 { 69 for ( loop5 = 0; loop5 <= 2; loop5++ ) 70 { 71 for ( loop6 = 0; loop6 <= 2; loop6++ ) 72 { 73 for ( loop7 = 0; loop7 <= 2; loop7++ ) 74 { 75 output.format( "%s%s%s%s%s%s%s\n", 76 letters[ digits[ 0 ] ][ loop1 ], 77 letters[ digits[ 1 ] ][ loop2 ], 78 letters[ digits[ 2 ] ][ loop3 ], 79 letters[ digits[ 3 ] ][ loop4 ], 80 letters[ digits[ 4 ] ][ loop5 ], 81 letters[ digits[ 5 ] ][ loop6 ], 82 letters[ digits[ 6 ] ][ loop7 ] ); 83 } // end for 84 } // end for 85 } // end for 86 } // end for 87 } // end for 88 } // end for 89 } // end for 90 } // end try 91 catch ( IllegalFormatException illegalFormatException ) 92 { 93 System.out.println( "Error in format of output." ); 94 System.exit( 1 ); 95 } // end catch 96 catch ( FormatterClosedException formatterClosedException ) 97 { 98 System.out.println( 99 "Error sending output; File has been closed." ); 100 System.exit( 1 ); 101 } // end catch 102 103 System.out.println( "Done" ); 104 105 output.close(); // close output stream 106 } // end method calculate 107 } // end class Phone 46 | P a g e Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Programming Challenge 1 Solution: PhoneTest.java // Testing the Phone class. import java.util.Scanner; import java.util.NoSuchElementException; public class PhoneTest { public static void main( String args[] ) { Scanner scanner = new Scanner( System.in ); Phone application = new Phone(); System.out.print( "Enter phone number (digits greater than 1 only): " ); try { application.calculate( scanner.nextInt() ); } // end try catch ( NoSuchElementException elementException ) { System.err.println( "Error inputting data." ); } // end catch } // end main } // end class PhoneTest Enter phone number (digits greater than 1 only): 5556789 Please wait... Done A small portion of the contents of file phone.txt after PhoneTest.java executes. JJJMPTW JJJMPTX JJJMPTY JJJMPUW JJJMPUX JJJMPUY ... 47 | P a g e Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ Lab sheet 5 Section: _ Postlab Activities Programming Challenges 6. (Student Poll) Figure 7.8 in Java How to Program contains an array of survey responses that is hard coded into the program. Suppose we wish to process survey results that are stored in a file. This exercise requires two separate programs. First, create an application that prompts the user for survey responses and outputs each response to a file. Use a Formatter to create a file called numbers.txt. Each integer should be written using method format. Then modify the program in Figure 7.8 to read the survey responses from numbers.txt. The responses should be read from the file by using a Scanner. Method nextInt should be used to input one integer at a time from the file. The program should continue to read responses until it reaches the end of file. The results should be output to the text file "output.txt". Solution 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 // Programming Challenge 2 Solution: CreateResults.java // Create poll results and output them to a file. import java.io.FileNotFoundException; import java.util.Formatter; import java.util.FormatterClosedException; import java.util.IllegalFormatException; import java.util.NoSuchElementException; import java.util.Scanner; public class CreateResults { private int getValue() { int result = -1; Scanner scanner = new Scanner( System.in ); // prompt the user for input System.out.print( "Enter integer result (1 - 10), -1 to quit: " ); try { result = scanner.nextInt(); } // end try catch ( NoSuchElementException noSuchElementException ) { System.err.println( "Error with input." ); System.exit( 1 ); } // end catch return result; } // end method getValue private void outputData() { Formatter pollNumbers = null; 48 | P a g e try { // create the output stream pollNumbers = new Formatter( "numbers.txt" ); int pollValue = getValue(); // get a number from the user CPCS 203 Student Name: _____________________________ 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 // test for the sentinel value while ( pollValue != -1 ) { // if the number is valid if ( pollValue > 0 && pollValue < 11 ) // write the value pollNumbers.format( "%d\n", pollValue ); pollValue = getValue(); // get another value } // end while pollNumbers.close(); // close the file } // end try catch( SecurityException securityException ) { System.err.println( "Error opening file." ); } // end catch catch( FileNotFoundException fileNotFoundException ) { System.err.println( "Output file cannot be found." ); } // end catch catch( IllegalFormatException illegalFormatException ) { System.err.println( "Error with the output's format." ); } // end catch catch( FormatterClosedException formatterClosedException ) { System.err.println( "File has been closed." ); } // end catch finally { if ( pollNumbers != null ) pollNumbers.close(); } // end finally } // end method outputData public static void main( String args[] ) { CreateResults application = new CreateResults(); application.outputData(); } // end main } // end class CreateResults 49 | P a g e Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 // Programming Challenge 2 Solution: StudentPoll.java // Read poll results from a file and output ratings. import java.io.File; import java.io.FileNotFoundException; import java.util.Formatter; import java.util.FormatterClosedException; import java.util.IllegalFormatException; import java.util.NoSuchElementException; import java.util.Scanner; public class StudentPoll { public void displayData() { int frequency[] = new int[ 11 ]; 50 | P a g e Formatter writer = null; Scanner pollNumbers = null; try { pollNumbers = new Scanner( new File( "numbers.txt" ) ); writer = new Formatter( "output.txt" ); writer.format( "%-12s%-12s\n", "Rating", "Frequency" ); // for each answer, use that value as subscript to // determine element to increment while ( pollNumbers.hasNext() ) ++frequency[ pollNumbers.nextInt() ]; // append frequencies to String output for ( int rating = 1; rating < frequency.length; rating++ ) writer.format( "%-12d%-12d\n", rating, frequency[ rating ] ); } // end try catch ( FileNotFoundException fileNotFoundException ) { System.err.println( "Error: Files cannot be opened." ); } // end catch catch ( FormatterClosedException formatterClosedException ) { System.err.println( "Error: Output file is closed." ); } // end catch catch ( SecurityException securityException ) { System.err.println( "Error opening file for writing." ); } // end catch catch ( IllegalFormatException illegalFormatException ) { System.err.println( "Error writing data to file." ); } // end catch catch ( NoSuchElementException noSuchElementException ) { System.err.println( "Error reading from file." ); } // end catch catch ( IllegalStateException illegalStateException ) { System.err.println( "Error: Input file is closed." ); } // end catch finally { if ( writer != null ) writer.close(); Lab sheet 5 Section: _ CPCS 203 Student Name: _____________________________ 66 67 68 69 70 71 1 2 3 4 5 6 7 8 9 10 11 if ( pollNumbers != null ) pollNumbers.close(); } // end finally } // end displayData } // end class StudentPoll // Programming Challenge 2 Solution: StudentPollTest.java // Testing the StudentPoll class. public class StudentPollTest { public static void main( String args[] ) { StudentPoll application = new StudentPoll(); application.displayData(); } // end main } // end class StudentPollTest 51 | P a g e Lab sheet 5 Section: _