1 / 38

Starting Out with Java: From Control Structures through Objects 5th edition By Tony Gaddis

Starting Out with Java: From Control Structures through Objects 5th edition By Tony Gaddis Source Code: Chapter 11. Code Listing 11-1 (BadArray.java) 1 /** 2 This program causes an error and crashes. 3 */ 4 5 public class BadArray 6 {

carrollk
Download Presentation

Starting Out with Java: From Control Structures through Objects 5th edition By Tony Gaddis

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 (inti = 0; i <= 3; i++) 15 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 " + 20 "the name of a file:"); 21 22 (Continued)

  4. (23 try 24 { 25 file = new File(fileName); 26 inputFile = new Scanner(file); // Scanner object throws exception 27 JOptionPane.showMessageDialog(null, 28 "The file was found."); 29 } 30 catch (FileNotFoundExceptione) 31 { 32 JOptionPane.showMessageDialog(null, 33 "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 " + 20 "the name of a file:"); 21 22 // Attempt to open the file. (Continued)

  6. 23 try 24 { 25 file = new File(fileName); 26 inputFile = new Scanner(file); 27 JOptionPane.showMessageDialog(null, 28 "The file was found."); 29 } 30 catch (FileNotFoundExceptione) 31 { 32 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. 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 { 15 number = Integer.parseInt(str); 16 } 17 catch (NumberFormatException e) 18 { 19 System.out.println("Conversion error: " + 20 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. 25 try 26 { 27 28 File file = new File(filename); 29 Scanner inputFile = new Scanner(file); 30 32 while (inputFile.hasNext()) 33 { 34 35 oneMonth = inputFile.nextDouble(); 36 38 totalSales += oneMonth; 41 months++; 42 } 43 44 inputFile.close(); (Continued)

  10. 48 averageSales = totalSales / months; 49 50 51 JOptionPane.showMessageDialog(null, 52 "Number of months: " + months + 53 "\nTotal Sales: $" + 54 dollar.format(totalSales) + 55 "\nAverage Sales: $" + 56 dollar.format(averageSales)); 57 } 58 catch(FileNotFoundExceptione) 59 { 60 // Thrown by the Scanner constructor 62 JOptionPane.showMessageDialog(null, 63 "The file " + filename + 64 " does not exist."); 65 } 66

  11. catch (InputMismatchException e) 67 { 68 // Thrown by the Scanner class's nextDouble 69 // method when a non-numeric value is found. 70 JOptionPane.showMessageDialog(null, 71 "Non-numeric data found " + 72 "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 = 23 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 { 33 filename = JOptionPane.showInputDialog( 34 "ERROR: " + filename + 35 " does not exist.\n" + 36 "Enter another file name: "); 37 inputFile = openFile(filename); 38 } 39 40 41 while (inputFile.hasNext()) 42 { 43 try 44 { 45 // Get a month's sales amount. (Continued)

  14. 46 oneMonth = inputFile.nextDouble(); 47 49 totalSales += oneMonth; 50 51 52 months++; 53 } 54 catch(InputMismatchException e) 55 { 56 57 JOptionPane.showMessageDialog(null, 58 "Non-numeric data found in the file.\n" + 59 "The invalid record will be skipped."); 60 61 // Skip past the invalid data. 62 inputFile.nextLine(); 63 } // 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, 74 "Number of months: " + months + 75 "\nTotal Sales: $" + 76 dollar.format(totalSales) + 77 "\nAverage Sales: $" + 78 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 { 97 File file = new File(filename); 98 scan = new Scanner(file); 99 } 100 catch(FileNotFoundException e) 101 { 102 scan = null; 103 } 104 105 returnscan; 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 { 17 // Open the file. 18 File file = new File("Numbers.txt"); 19 Scanner inputFile = new Scanner(file); 20 21 // Process the contents of the file. 22 while (inputFile.hasNext()) (Continued)

  20. (Continued) Code Listing 11-8 (MultiCatch.java) 23 { 24 // Get a number from the file. 25 number = inputFile.nextInt(); 26 27 // Display the number. 28 System.out.println(number); 29 } 30 31 // Close the file. 32 I nputFile.close(); 33 } 34 catch(FileNotFoundException | InputMismatchException ex) 35 { 36 // Display an error message. 37 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 { 17 DateComponent dc = new DateComponent(str); 18 } 19 catch (IllegalArgumentException e) 20 { 21 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 8 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: " + 29 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 { 13 BankAccount account = 14 new BankAccount(-100.0); 15 } 16 catch(NegativeStartingBalance e) 17 { 18 System.out.println(e.getMessage()); 19 } 20 } 21 } Program Output Error: Negative starting balance: -100.0

  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) 11 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 = 18 new FileOutputStream("Numbers.dat"); 19 DataOutputStream outputFile = 20 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++) 26 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) 11 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 = 18 new FileInputStream("Numbers.dat"); 19 DataInputStream inputFile = 20 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 { 27 try 28 { 29 number = inputFile.readInt(); 30 System.out.print(number + " "); 31 } 32 catch (EOFException e) 33 { 34 endOfFile = true; 35 } 36 } 37 38 System.out.println("\nDone."); 39 40 // Close the file. 41 inputFile.close(); 42 } 43 } Program Output Reading numbers from the file: 2 4 6 8 10 12 14 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) 12 throws IOException 13 { 14 // The letters array has all 26 letters. 15 char[] letters = { 16 'a', 'b', 'c', 'd', 'e', 'f', 'g', 17 'h', 'i', 'j', 'k', 'l', 'm', 'n', 18 'o', 'p', 'q', 'r', 's', 't', 'u', 19 '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++) 31 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 = 19 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) 12 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 = 22 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 " + 29 "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 = 38 new FileOutputStream("Objects.dat"); 39 ObjectOutputStream objectOutputFile = 40 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 " + 52 "were written to the Objects.dat file."); 53 } 54 } Program Output with Example Input Shown in Bold Enter the balance for account 1: 5000.0 [Enter] Enter the balance for account 2: 2500.0 [Enter] Enter the balance for account 3: 1800.0 [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) 11 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 = 18 new FileInputStream("Objects.dat"); 19 ObjectInputStream objectInputFile = 20 new ObjectInputStream(inStream); 21 22 // Create a BankAccount2 array 23 BankAccount2[] accounts = (Continued)

  38. (Continued) Code Listing 11-17 (DeserializeObjects.java) 24 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] = 30 (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) + 40 " $ " + accounts[i].getBalance()); 41 } 42 } 43 } Program Output Account 1 $ 5000.0 Account 2 $ 2500.0 Account 3 $ 1800.0

More Related