Download presentation
Presentation is loading. Please wait.
Published byClarence McCormick Modified over 6 years ago
1
Starting Out with Java: From Control Structures through Objects
5th edition By Tony Gaddis Source Code: Chapter 11
2
Code Listing 11-1 (BadArray.java)
1 /** 2 This program causes an error and crashes. 3 */ 4 5 public class BadArray 6 { 7 public static void main(String[] args) 8 { 9 10 int[] numbers = { 1, 2, 3 }; 11 12 14 for (int i = 0; i <= 3; i++) System.out.println(numbers[i]); 16 } 17 } Program Output 1 2 3 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at BadArray.main(BadArray.java:15)
3
Code Listing 11-2 (OpenFile.java)
import java.io.*; // For File class and //FileNotFoundException 2 import java.util.Scanner; // For the Scanner class 3 import javax.swing.JOptionPane; // For the JOptionPane class 4 5 /** 6 This program demonstrates how a FileNotFoundException 7 exception can be handled. 8 */ 9 10 public class OpenFile 11 { 12 public static void main(String[] args) 13 { 14 File file; 15 Scanner inputFile; 16 String fileName; 17 18 // Get a file name from the user. 19 fileName = JOptionPane.showInputDialog("Enter " + "the name of a file:"); 21 22 (Continued)
4
(23 try 24 { 25 file = new File(fileName);
24 { file = new File(fileName); inputFile = new Scanner(file); // Scanner object throws exception JOptionPane.showMessageDialog(null, "The file was found."); 29 } 30 catch (FileNotFoundException e) 31 { JOptionPane.showMessageDialog(null, "File not found."); 34 } 35 36 JOptionPane.showMessageDialog(null, "Done."); 37 System.exit(0); 38 } 39 }
5
Code Listing 11-3 (ExceptionMessage.java)
1 import java.io.*; // For file I/O classes 2 import java.util.Scanner; // For the Scanner class 3 import javax.swing.JOptionPane; // For the JOptionPane class 4 5 /** 6 This program demonstrates how a FileNotFoundException 7 exception can be handled. 8 */ 9 10 public class ExceptionMessage 11 { 12 public static void main(String[] args) 13 { 14 File file; 15 Scanner inputFile; 16 String fileName; 17 18 19 fileName = JOptionPane.showInputDialog("Enter " + "the name of a file:"); 21 22 // Attempt to open the file. (Continued)
6
23 try 24 { file = new File(fileName); inputFile = new Scanner(file); JOptionPane.showMessageDialog(null, "The file was found."); 29 } 30 catch (FileNotFoundException e) 31 { JOptionPane.showMessageDialog(null, e.getMessage()); 33 } 34 JOptionPane.showMessageDialog(null, "Done."); 36 System.exit(0); 37 } } Each exception object has a method names “ getMessage()” that can be used to retrieve the default error message for that exception.
7
Conversion error: For input string: "abcde"
Code Listing 11-4 (ParseIntError.java) 1 /** 2 This program demonstrates how the Integer.parseInt 3 method throws an exception. 4 */ 5 6 public class ParseIntError 7 { 8 public static void main(String[] args) 9 { 10 String str = "abcde"; 11 int number; 12 13 try 14 { number = Integer.parseInt(str); 16 } 17 catch (NumberFormatException e) 18 { System.out.println("Conversion error: " + e.getMessage()); 21 } 22 } 23 } Program Output Conversion error: For input string: "abcde"
8
Code Listing 11-5 (SalesReport.java)
import java.io.*; // For File class and // FileNotFoundException 2 import java.util.*; // For Scanner and // InputMismatchException 3 import java.text.DecimalFormat; // For the DecimalFormat class 4 import javax.swing.JOptionPane; // For the JOptionPane class 5 6 /** 7 This program demonstrates how multiple exceptions can 8 be caught with one try statement. 9 */ 10 11 public class SalesReport 12 { 13 public static void main(String[] args) 14 { 15 String filename = "SalesData.txt"; // File name 16 int months = 0; 17 double oneMonth; // One month's sales 18 double totalSales = 0.0; // Total sales 19 double averageSales; // Average sales 20 22 DecimalFormat dollar = new DecimalFormat(“#,##0.00”);
9
28 File file = new File(filename);
25 try 26 { 27 File file = new File(filename); Scanner inputFile = new Scanner(file); 30 while (inputFile.hasNext()) { 34 oneMonth = inputFile.nextDouble(); 36 totalSales += oneMonth; months++; } 43 inputFile.close(); (Continued)
10
48 averageSales = totalSales / months;
49 50 JOptionPane.showMessageDialog(null, "Number of months: " + months + "\nTotal Sales: $" + dollar.format(totalSales) + "\nAverage Sales: $" + dollar.format(averageSales)); 57 } 58 catch(FileNotFoundException e) 59 { // Thrown by the Scanner constructor JOptionPane.showMessageDialog(null, "The file " + filename + " does not exist."); 65 } 66
11
catch (InputMismatchException e)
67 { // Thrown by the Scanner class's nextDouble // method when a non-numeric value is found. JOptionPane.showMessageDialog(null, "Non-numeric data found " + "in the file."); 73 } 74 75 System.exit(0); 76 } 77 }
12
Code Listing 11-6 (SalesReport2.java)
1 import java.io.*; 2 import java.util.*; 3 import java.text.DecimalFormat; 4 import javax.swing.JOptionPane; 5 6 /** 7 This program demonstrates how exception handlers can 8 be used to recover from errors. 9 */ 10 11 public class SalesReport2 12 { 13 public static void main(String[] args) 14 { 15 String filename = "SalesData.txt"; 16 int months = 0; 17 double oneMonth; 18 double totalSales = 0.0; 19 double averageSales; 20 22 DecimalFormat dollar = new DecimalFormat("#,##0.00");
13
27 Scanner inputFile = openFile(filename);
28 29 // If the openFile method returned null, then // the file was not found. Get a new file name. 31 while (inputFile == null) 32 { filename = JOptionPane.showInputDialog( "ERROR: " + filename + " does not exist.\n" + "Enter another file name: "); inputFile = openFile(filename); 38 } 39 40 41 while (inputFile.hasNext()) 42 { try { // Get a month's sales amount. (Continued)
14
46 oneMonth = inputFile.nextDouble();
47 totalSales += oneMonth; 50 51 months++; } catch(InputMismatchException e) { 56 JOptionPane.showMessageDialog(null, "Non-numeric data found in the file.\n" + "The invalid record will be skipped."); 60 // Skip past the invalid data. inputFile.nextLine(); } // END OF CATCH BLOCK 64 }// END OF WHILE LOOP 65 66 // Close the file. 67 inputFile.close(); (Continued)
15
70 averageSales = totalSales / months; 71 72 // Display the results.
73 JOptionPane.showMessageDialog(null, "Number of months: " + months + "\nTotal Sales: $" + dollar.format(totalSales) + "\nAverage Sales: $" + dollar.format(averageSales)); 79 System.exit(0); // END OF MAIN() 80 } 81 82 /** 83 The openFile method opens the specified file and 84 returns a reference to a Scanner object. 85 @param filename The name of the file to open. 86 @return A Scanner reference, if the file exists 87 Otherwise, null is returned. 88 */ 89 (Continued)
16
90 public static Scanner openFile(String filename)
91 { 92 Scanner scan; 93 95 try 96 { File file = new File(filename); scan = new Scanner(file); 99 } 100 catch(FileNotFoundException e) { scan = null; } 104 105 return scan; 106 } 107 }
17
Code Listing 11-7 (StackTrace.java)
1 /** 2 This program demonstrates the stack trace that is 3 produced when an exception is thrown. 4 */ 5 6 public class StackTrace 7 { 8 public static void main(String[] args) 9 { 10 System.out.println("Calling myMethod..."); 11 myMethod(); 12 System.out.println("Method main is done."); 13 } 14 15 /** 16 MyMethod 17 */ 18 19 public static void myMethod() 20 { 21 System.out.println("Calling produceError..."); 22 produceError(); (Continued)
18
23 System.out.println("myMethod is done.");
24 } 25 26 /** 27 produceError 28 */ 29 30 public static void produceError() 31 { 32 String str = "abc"; 33 34 // The following statement will cause an error. 35 System.out.println(str.charAt(3)); 36 System.out.println("produceError is done."); 37 } } Program Output Calling myMethod... Calling produceError... Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3 at java.lang.String.charAt(Unknown Source) at StackTrace.produceError(StackTrace.java:35) at StackTrace.myMethod(StackTrace.java:22) at StackTrace.main(StackTrace.java:11)
19
Code Listing 11-8 (MultiCatch.java)
1 import java.io.*; // For File class and FileNotFoundException 2 import java.util.*; // For Scanner and InputMismatchException 3 4 /** 5 This program demonstrates how multiple exceptions can 6 be caught with a single catch clause. 7 */ 8 9 public class MultiCatch 10 { 11 public static void main(String[] args) 12 { 13 int number; // To hold a number from the file 14 15 try 16 { // Open the file. File file = new File("Numbers.txt"); Scanner inputFile = new Scanner(file); 20 // Process the contents of the file. while (inputFile.hasNext()) (Continued)
20
(Continued) Code Listing 11-8 (MultiCatch.java)
{ // Get a number from the file. number = inputFile.nextInt(); 26 // Display the number. System.out.println(number); } 30 // Close the file. 32 I nputFile.close(); 33 } 34 catch(FileNotFoundException | InputMismatchException ex) 35 { // Display an error message. System.out.println("Error processing the file."); 38 } 39 } 40 }
21
Code Listing 11-9 (DateComponentExceptionDemo.java)
1 /** 2 This program demonstrates how the DateComponent 3 class constructor throws an exception. 4 */ 5 6 public class DateComponentExceptionDemo 7 { 8 public static void main(String[] args) 9 { 10 // Create a null String reference. 11 String str = null; 12 13 // Attempt to pass the null reference to 14 // the DateComponent constructor. 15 try 16 { DateComponent dc = new DateComponent(str); 18 } 19 catch (IllegalArgumentException e) 20 { System.out.println(e.getMessage()); 22 } 23 } 24 } Program Output null reference passed to DateComponent constructor
22
Code Listing 11-10 (NegativeStartingBalance.java)
1 /** 2 NegativeStartingBalance exceptions are thrown by the 3 BankAccount class when a negative starting balance is 4 passed to the constructor. 5 */ 6 7 public class NegativeStartingBalance extends Exception 9 { 10 /** 11 This constructor uses a generic 12 error message. 13 */ 14 15 public NegativeStartingBalance() 16 { 17 super("Error: Negative starting balance"); 18 } 19 20 /** 21 This constructor specifies the bad starting 22 balance in the error message. (Continued)
23
(Continued) Code Listing 11-10 (NegativeStartingBalance.java)
23 @param The bad starting balance. 24 */ 25 26 public NegativeStartingBalance(double amount) 27 { 28 super("Error: Negative starting balance: " + amount); 30 } 31 }
24
Code Listing 11-11 (AccountTest.java)
1 /** 2 This program demonstrates how the BankAccount 3 class constructor throws custom exceptions. 4 */ 5 6 public class AccountTest 7 { 8 public static void main(String [] args) 9 { 10 // Force a NegativeStartingBalance exception. 11 try 12 { BankAccount account = new BankAccount(-100.0); 15 } 16 catch(NegativeStartingBalance e) 17 { System.out.println(e.getMessage()); 19 } 20 } 21 } Program Output Error: Negative starting balance:
25
Code Listing 11-12 (WriteBinaryFile.java)
1 import java.io.*; 2 3 /** 4 This program opens a binary file and writes the contents 5 of an int array to the file. 6 */ 7 8 public class WriteBinaryFile 9 { 10 public static void main(String[] args) throws IOException 12 { 13 // An array to write to the file 14 int[] numbers = { 2, 4, 6, 8, 10, 12, 14 }; 15 16 // Create the binary output objects. 17 FileOutputStream fstream = new FileOutputStream("Numbers.dat"); 19 DataOutputStream outputFile = new DataOutputStream(fstream); 21 22 System.out.println("Writing the numbers to the file..."); (Continued)
26
(Continued) Code Listing 11-12 (WriteBinaryFile.java)
23 24 // Write the array elements to the file. 25 for (int i = 0; i < numbers.length; i++) outputFile.writeInt(numbers[i]); 27 28 System.out.println("Done."); 29 30 // Close the file. 31 outputFile.close(); 32 } 33 } Program Output Writing the numbers to the file... Done.
27
Code Listing 11-13 (ReadBinaryFile.java)
1 import java.io.*; 2 3 /** 4 This program opens a binary file, reads 5 and displays the contents. 6 */ 7 8 public class ReadBinaryFile 9 { 10 public static void main(String[] args) throws IOException 12 { 13 int number; // A number read from the file 14 boolean endOfFile = false; // EOF flag 15 16 // Create the binary file input objects. 17 FileInputStream fstream = new FileInputStream("Numbers.dat"); 19 DataInputStream inputFile = new DataInputStream(fstream); 21 22 System.out.println("Reading numbers from the file:"); (Continued)
28
(Continued) Code Listing 11-13 (ReadBinaryFile.java)
23 24 // Read the contents of the file. 25 while (!endOfFile) 26 { try { number = inputFile.readInt(); System.out.print(number + " "); } catch (EOFException e) { endOfFile = true; } 36 } 37 38 System.out.println("\nDone."); 39 40 // Close the file. 41 inputFile.close(); 42 } 43 } Program Output Reading numbers from the file: Done.
29
Code Listing 11-14 (WriteLetters.java)
1 import java.io.*; 2 3 /** 4 This program uses a RandomAccessFile object to 5 create the file Letters.dat. The letters of the 6 alphabet are written to the file. 7 */ 8 9 public class WriteLetters 10 { 11 public static void main(String[] args) throws IOException 13 { 14 // The letters array has all 26 letters. 15 char[] letters = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; 20 21 System.out.println("Opening the file."); 22 23 // Open a file for reading and writing. (Continued)
30
(Continued) Code Listing 11-14 (WriteLetters.java)
24 RandomAccessFile randomFile = 25 new RandomAccessFile("Letters.dat", "rw"); 26 27 System.out.println("Writing data to the file..."); 28 29 // Sequentially write the letters array to the file. 30 for (int i = 0; i < letters.length; i++) randomFile.writeChar(letters[i]); 32 33 // Close the file. 34 randomFile.close(); 35 36 System.out.println("Done."); 37 } 38 } Program Output Opening the file. Writing data to the file... Done.
31
Code Listing 11-15 (ReadRandomLetters.java)
1 import java.io.*; 2 3 /** 4 This program uses the RandomAccessFile class to open 5 the file Letters.dat and randomly read letters from 6 different locations. 7 */ 8 9 public class ReadRandomLetters 10 { 11 public static void main(String[] args) throws IOException 12 { 13 final int CHAR_SIZE = 2; // 2 byte characters 14 long byteNum; // The byte number 15 char ch; // A character from the file 16 17 // Open the file for reading. 18 RandomAccessFile randomFile = new RandomAccessFile("Letters.dat", "r"); 20 21 // Move to the character 5. This is the 6th 22 // character from the beginning of the file. (Continued)
32
(Continued) Code Listing 11-15 (ReadRandomLetters.java)
23 byteNum = CHAR_SIZE * 5; 24 randomFile.seek(byteNum); 25 26 // Read the character stored at this location 27 // and display it. Should be the letter f. 28 ch = randomFile.readChar(); 29 System.out.println(ch); 30 31 // Move to character 10 (the 11th character), 32 // read the character, and display it. 33 // Should be the letter k. 34 byteNum = CHAR_SIZE * 10; 35 randomFile.seek(byteNum); 36 ch = randomFile.readChar(); 37 System.out.println(ch); 38 39 // Move to character 3 (the 4th character), 40 // read the character, and display it. 41 // Should be the letter d. 42 byteNum = CHAR_SIZE * 3; 43 randomFile.seek(byteNum); 44 ch = randomFile.readChar(); (Continued)
33
(Continued) Code Listing 11-15 (ReadRandomLetters.java)
45 System.out.println(ch); 46 47 // Close the file. 48 randomFile.close(); 49 } 50 } Program Output f k d
34
Code Listing 11-16 (SerializeObjects.java)
1 import java.io.*; 2 import java.util.Scanner; 3 4 /** 5 This program serializes the objects in an array of 6 BankAccount2 objects. 7 */ 8 9 public class SerializeObjects 10 { 11 public static void main(String[] args) throws IOException 13 { 14 double balance; // An account balance 15 final int NUM_ITEMS = 3; // Number of accounts 16 17 // Create a Scanner object for keyboard input. 18 Scanner keyboard = new Scanner(System.in); 19 20 // Create a BankAccount2 array 21 BankAccount2[] accounts = new BankAccount2[NUM_ITEMS]; (Continued)
35
(Continued) Code Listing 11-16 (SerializeObjects.java)
23 24 // Populate the array. 25 for (int i = 0; i < accounts.length; i++) 26 { 27 // Get an account balance. 28 System.out.print("Enter the balance for " + "account " + (i + 1) + ": "); 30 balance = keyboard.nextDouble(); 31 32 // Create an object in the array. 33 accounts[i] = new BankAccount2(balance); 34 } 35 36 // Create the stream objects. 37 FileOutputStream outStream = new FileOutputStream("Objects.dat"); 39 ObjectOutputStream objectOutputFile = new ObjectOutputStream(outStream); 41 42 // Write the serialized objects to the file. 43 for (int i = 0; i < accounts.length; i++) 44 { (Continued)
36
(Continued) Code Listing 11-16 (SerializeObjects.java)
45 objectOutputFile.writeObject(accounts[i]); 46 } 47 48 // Close the file. 49 objectOutputFile.close(); 50 51 System.out.println("The serialized objects " + "were written to the Objects.dat file."); 53 } 54 } Program Output with Example Input Shown in Bold Enter the balance for account 1: [Enter] Enter the balance for account 2: [Enter] Enter the balance for account 3: [Enter] The serialized objects were written to the Objects.dat file.
37
Code Listing 11-17 (DeserializeObjects.java)
1 import java.io.*; 2 3 /** 4 This program deserializes the objects in the Objects.dat 5 file and stores them in an array. 6 */ 7 8 public class DeserializeObjects 9 { 10 public static void main(String[] args) throws Exception 12 { 13 double balance; // An account balance 14 final int NUM_ITEMS = 3; // Number of accounts 15 16 // Create the stream objects. 17 FileInputStream inStream = new FileInputStream("Objects.dat"); 19 ObjectInputStream objectInputFile = new ObjectInputStream(inStream); 21 22 // Create a BankAccount2 array 23 BankAccount2[] accounts = (Continued)
38
(Continued) Code Listing 11-17 (DeserializeObjects.java)
new BankAccount2[NUM_ITEMS]; 25 26 // Read the serialized objects from the file. 27 for (int i = 0; i < accounts.length; i++) 28 { 29 accounts[i] = (BankAccount2) objectInputFile.readObject(); 31 } 32 33 // Close the file. 34 objectInputFile.close(); 35 36 // Display the objects. 37 for (int i = 0; i < accounts.length; i++) 38 { 39 System.out.println("Account " + (i + 1) + " $ " + accounts[i].getBalance()); 41 } 42 } 43 } Program Output Account 1 $ Account 2 $ Account 3 $
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.