Download Code Listing 11-1 - CS Course Webpages

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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 {
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++)
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)
Code Listing 11-2 (OpenFile.java)
1
2
2
3
4
5
6
7
import java.io.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
// For File class and
//FileNotFoundException
// For the Scanner class
// For the JOptionPane class
/**
This program demonstrates how a FileNotFoundException
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)
(23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
try
{
file = new File(fileName);
inputFile = new Scanner(file); // Scanner object throws exception
JOptionPane.showMessageDialog(null,
"The file was found.");
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(null,
"File not found.");
}
JOptionPane.showMessageDialog(null, "Done.");
System.exit(0);
}
}
Code Listing 11-3 (ExceptionMessage.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
// For file I/O classes
// For the Scanner class
// For the JOptionPane class
/**
This program demonstrates how a FileNotFoundException
exception can be handled.
*/
public class ExceptionMessage
{
public static void main(String[] args)
{
File file;
Scanner inputFile;
String fileName;
fileName = JOptionPane.showInputDialog("Enter " +
"the name of a file:");
// Attempt to open the file.
(Continued)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 }
try
{
file = new File(fileName);
inputFile = new Scanner(file);
JOptionPane.showMessageDialog(null,
"The file was found.");
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(null, e.getMessage());
}
JOptionPane.showMessageDialog(null, "Done.");
System.exit(0);
}
Each exception object has a method names “ getMessage()” that can
be used to retrieve the default error message for that exception.
Code Listing 11-4 (ParseIntError.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
This program demonstrates how the Integer.parseInt
method throws an exception.
*/
public class ParseIntError
{
public static void main(String[] args)
{
String str = "abcde";
int number;
try
{
number = Integer.parseInt(str);
}
catch
(NumberFormatException e)
{
20
21
}
22
}
23 }
Program Output
System.out.println("Conversion error: " +
e.getMessage());
Conversion error: For input string: "abcde"
Code Listing 11-5 (SalesReport.java)
1
2
2
import java.io.*;
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
22
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
import java.util.*;
// For File class and
// FileNotFoundException
// For Scanner and
// InputMismatchException
// For the DecimalFormat class
// For the JOptionPane class
/**
This program demonstrates how multiple exceptions can
be caught with one try statement.
*/
public class SalesReport
{
public static void main(String[] args)
{
String filename = "SalesData.txt";
int months = 0;
double oneMonth;
double totalSales = 0.0;
double averageSales;
// File name
// One month's sales
// Total sales
// Average sales
DecimalFormat dollar = new DecimalFormat(“#,##0.00”);
25
26
27
28
29
30
32
33
34
35
36
38
41
42
43
44
try
{
File file = new File(filename);
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{
oneMonth = inputFile.nextDouble();
totalSales += oneMonth;
months++;
}
inputFile.close();
(Continued)
48
49
50
51
52
53
54
55
56
57
58
59
60
62
63
64
65
66
averageSales = totalSales / months;
JOptionPane.showMessageDialog(null,
"Number of months: " + months +
"\nTotal Sales: $" +
dollar.format(totalSales) +
"\nAverage Sales: $" +
dollar.format(averageSales));
}
catch(FileNotFoundException
e)
{
// Thrown by the Scanner constructor
JOptionPane.showMessageDialog(null,
"The file " + filename +
" does not exist.");
}
catch (InputMismatchException
67
68
69
70
71
72
73
74
75
76
77
e)
{
// 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.");
}
System.exit(0);
}
}
Code Listing 11-6 (SalesReport2.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
22
23
import
import
import
import
java.io.*;
java.util.*;
java.text.DecimalFormat;
javax.swing.JOptionPane;
/**
This program demonstrates how exception handlers can
be used to recover from errors.
*/
public class SalesReport2
{
public static void main(String[] args)
{
String filename = "SalesData.txt";
int months = 0;
double oneMonth;
double totalSales = 0.0;
double averageSales;
DecimalFormat dollar =
new DecimalFormat("#,##0.00");
openFile(filename);
27
Scanner inputFile =
28
29
30
// If the openFile method returned null, then
// the file was not found. Get a new file name.
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
while (inputFile == null)
{
filename = JOptionPane.showInputDialog(
"ERROR: " + filename +
" does not exist.\n" +
"Enter another file name: ");
inputFile = openFile(filename);
}
while (inputFile.hasNext())
{
try
{
// Get a month's sales amount.
(Continued)
46
47
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
oneMonth = inputFile.nextDouble();
totalSales += oneMonth;
months++;
}
catch(InputMismatchException
e)
{
JOptionPane.showMessageDialog(null,
"Non-numeric data found in the file.\n" +
"The invalid record will be skipped.");
// Skip past the invalid data.
inputFile.nextLine();
} // END OF CATCH BLOCK
}// END OF WHILE LOOP
// Close the file.
inputFile.close();
(Continued)
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
averageSales = totalSales / months;
// Display the results.
JOptionPane.showMessageDialog(null,
"Number of months: " + months +
"\nTotal Sales: $" +
dollar.format(totalSales) +
"\nAverage Sales: $" +
dollar.format(averageSales));
System.exit(0);
//
END OF MAIN()
}
/**
The openFile method opens the specified file and
returns a reference to a Scanner object.
@param filename The name of the file to open.
@return A Scanner reference, if the file exists
Otherwise, null is returned.
*/
(Continued)
90
91
92
93
95
96
97
98
99
100
101
102
103
104
105
106
107 }
public static Scanner openFile(String filename)
{
Scanner scan;
try
{
File file = new File(filename);
scan = new Scanner(file);
}
catch(FileNotFoundException e)
{
scan = null;
}
return scan;
}
Code Listing 11-7 (StackTrace.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
This program demonstrates the stack trace that is
produced when an exception is thrown.
*/
public class StackTrace
{
public static void main(String[] args)
{
System.out.println("Calling myMethod...");
myMethod();
System.out.println("Method main is done.");
}
/**
MyMethod
*/
public static void myMethod()
{
System.out.println("Calling produceError...");
produceError();
(Continued)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 }
System.out.println("myMethod is done.");
}
/**
produceError
*/
public static void produceError()
{
String str = "abc";
// The following statement will cause an error.
System.out.println(str.charAt(3));
System.out.println("produceError is done.");
}
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)
Code Listing 11-8 (MultiCatch.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.*;
import java.util.*;
// For File class and FileNotFoundException
// For Scanner and InputMismatchException
/**
This program demonstrates how multiple exceptions can
be caught with a single catch clause.
*/
public class MultiCatch
{
public static void main(String[] args)
{
int number;
// To hold a number from the file
try
{
// Open the file.
File file = new File("Numbers.txt");
Scanner inputFile = new Scanner(file);
// Process the contents of the file.
while (inputFile.hasNext())
(Continued)
(Continued) Code Listing 11-8 (MultiCatch.java)
23
24
25
26
27
28
29
30
31
32 I
33
34
35
36
37
38
39
40 }
{
// Get a number from the file.
number = inputFile.nextInt();
// Display the number.
System.out.println(number);
}
// Close the file.
nputFile.close();
}
catch(FileNotFoundException | InputMismatchException ex)
{
// Display an error message.
System.out.println("Error processing the file.");
}
}
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
Code Listing 11-10 (NegativeStartingBalance.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
NegativeStartingBalance exceptions are thrown by the
BankAccount class when a negative starting balance is
passed to the constructor.
*/
public class NegativeStartingBalance
extends Exception
{
/**
This constructor uses a generic
error message.
*/
public NegativeStartingBalance()
{
super("Error: Negative starting balance");
}
/**
This constructor specifies the bad starting
balance in the error message.
(Continued)
(Continued) Code Listing 11-10
(NegativeStartingBalance.java)
23
24
25
26
27
28
29
30
31
@param The bad starting balance.
*/
public NegativeStartingBalance(double amount)
{
super("Error: Negative starting balance: " +
amount);
}
}
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
Code Listing 11-12 (WriteBinaryFile.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.*;
/**
This program opens a binary file and writes the contents
of an int array to the file.
*/
public class WriteBinaryFile
{
public static void main(String[] args)
throws IOException
{
// An array to write to the file
int[] numbers = { 2, 4, 6, 8, 10, 12, 14 };
// Create the binary output objects.
FileOutputStream fstream =
new FileOutputStream("Numbers.dat");
DataOutputStream outputFile =
new DataOutputStream(fstream);
System.out.println("Writing the numbers to the file...");
(Continued)
(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.
Code Listing 11-13 (ReadBinaryFile.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.*;
/**
This program opens a binary file, reads
and displays the contents.
*/
public class ReadBinaryFile
{
public static void main(String[] args)
throws IOException
{
int number;
// A number read from the file
boolean endOfFile = false;
// EOF flag
// Create the binary file input objects.
FileInputStream fstream =
new FileInputStream("Numbers.dat");
DataInputStream inputFile =
new DataInputStream(fstream);
System.out.println("Reading numbers from the file:");
(Continued)
(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
Code Listing 11-14 (WriteLetters.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.io.*;
/**
This program uses a RandomAccessFile object to
create the file Letters.dat. The letters of the
alphabet are written to the file.
*/
public class WriteLetters
{
public static void main(String[] args)
throws IOException
{
// The letters array has all 26 letters.
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' };
System.out.println("Opening the file.");
// Open a file for reading and writing.
(Continued)
(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.
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)
(Continued) Code Listing 11-15 (ReadRandomLetters.java)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
byteNum = CHAR_SIZE * 5;
randomFile.seek(byteNum);
// Read the character stored at this location
// and display it. Should be the letter f.
ch = randomFile.readChar();
System.out.println(ch);
// Move to character 10 (the 11th character),
// read the character, and display it.
// Should be the letter k.
byteNum = CHAR_SIZE * 10;
randomFile.seek(byteNum);
ch = randomFile.readChar();
System.out.println(ch);
// Move to character 3 (the 4th character),
// read the character, and display it.
// Should be the letter d.
byteNum = CHAR_SIZE * 3;
randomFile.seek(byteNum);
ch = randomFile.readChar();
(Continued)
(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
Code Listing 11-16 (SerializeObjects.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.*;
import java.util.Scanner;
/**
This program serializes the objects in an array of
BankAccount2 objects.
*/
public class SerializeObjects
{
public static void main(String[] args)
throws IOException
{
double balance;
// An account balance
final int NUM_ITEMS = 3; // Number of accounts
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Create a BankAccount2 array
BankAccount2[] accounts =
new BankAccount2[NUM_ITEMS];
(Continued)
(Continued) Code Listing 11-16 (SerializeObjects.java)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Populate the array.
for (int i = 0; i < accounts.length; i++)
{
// Get an account balance.
System.out.print("Enter the balance for " +
"account " + (i + 1) + ": ");
balance = keyboard.nextDouble();
// Create an object in the array.
accounts[i] = new BankAccount2(balance);
}
// Create the stream objects.
FileOutputStream outStream =
new FileOutputStream("Objects.dat");
ObjectOutputStream objectOutputFile =
new ObjectOutputStream(outStream);
// Write the serialized objects to the file.
for (int i = 0; i < accounts.length; i++)
{
(Continued)
(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.
Code Listing 11-17 (DeserializeObjects.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.io.*;
/**
This program deserializes the objects in the Objects.dat
file and stores them in an array.
*/
public class DeserializeObjects
{
public static void main(String[] args)
throws Exception
{
double balance;
// An account balance
final int NUM_ITEMS = 3; // Number of accounts
// Create the stream objects.
FileInputStream inStream =
new FileInputStream("Objects.dat");
ObjectInputStream objectInputFile =
new ObjectInputStream(inStream);
// Create a BankAccount2 array
BankAccount2[] accounts =
(Continued)
(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