ch04 - udcompsci

Download Report

Transcript ch04 - udcompsci

Object-Oriented Program Development
Using Java: A Class-Centered Approach,
Enhanced Edition
Objectives
You should be able to describe:
• Interactive Keyboard Input
• Interactive Dialog Input
• Creating a Class Library
• Formatted Output
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
2
Objectives (continued)
• Mathematical Methods
• Common Programming Errors
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
3
Interactive Keyboard Input
• Interactive data is entered:
– By user at keyboard
– Via graphical user interface (GUI)
– From file
• Data can be entered into program while it is
running using System.in object
• Stream objects
– Called streams for short
– Transmit data as stream of individual data bytes
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
4
Interactive Keyboard Input
(continued)
• End-of-file (EOF) marker
– Special end-of-data value
– Numerical value that cannot be converted into
legitimate character value
• Would like to read an entire line at once
– Use supporting classes:
• InputStreamReader
• BufferedReader
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
5
Interactive Keyboard Input
(continued)
Figure 4.2: Generating the EOF value
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
6
Interactive Keyboard Input
(continued)
• InputStreamReader
– Automatically converts integer values of
System.in stream to character values
– Can be constructed from System.in object
– InputStreamReader isr =
new InputStreamReader(System.in);
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
7
Interactive Keyboard Input
(continued)
• BufferedReader
– Automatically constructs string from character
values provided by InputStreamReader
object
– BufferedReader br = new BufferedReader(isr);
• Display prompt
– Asks user to enter data
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
8
Interactive Keyboard Input
(continued)
• Calling readLine()
– Puts system in wait state
– Until user types data
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
9
Interactive Keyboard Input
(continued)
Table 4.1: Keyboard Input Classes and Methods
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
10
Interactive Keyboard Input
(continued)
Table 4.2: Java Conversion Routines
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
11
The StringTokenizer Class
• Token
– String of characters separated by delimiting
character
• Delimiting characters
– Whitespace by default in Java
• Parsing the string
– Separating individual tokens from string
• Class StringTokenizer
– Used to parse strings
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
12
The StringTokenizer Class
(continued)
Figure 4.5: Parsing tokens from a string
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
13
The Scanner Class
• Provides simpler way to read numerical input
– No need to perform data type conversion
• Example:
Scanner sc = new
Scanner(System.in);
double num1 = sc.nextDouble();
• java.util.Formatter class
– Process more complex input
– Includes pattern matching algorithms
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
14
The Scanner Class (continued)
Table 4.3: Commonly Used Scanner Class
Input Methods
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
15
A First Look at User-Input Validation
• Well-constructed program
– Validates user input
– Does not crash due to unexpected input
• Crash
– Program termination caused by unexpected error
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
16
A First Look at User-Input Validation
(continued)
Figure 4.6: A NumberFormatException
notification
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
17
A First Look at User-Input Validation
(continued)
• Consists of:
– Validating entered data either during or
immediately after data have been entered
– Providing user with way of reentering any invalid
data
• To handle invalid input provide error processing
code
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
18
A First Look at User-Input Validation
(continued)
• Throwing error up to operating system
– Use reserved word throws with error name
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
19
Interactive Dialog Input
• GUI method of entering user data:
– Method named showInputDialog()in
JOptionPane class
• Creates dialog box that permits user to enter string
• Syntax:
JOptionPane.showInputDialog(string);
• Example:
s = JOptionPane.showInputDialog("Enter number:");
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
20
Interactive Dialog Input
Figure 4.7: A sample showInputDialog()
dialog
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
21
Exception Handling
• Error handling in Java different from other highlevel languages
• Exception handling
– Error occurs while method is running
– Method creates object that contains information
about error
– Object immediately passed to Java Virtual Machine
– JVM attempts to locate code to handle exception
– Called throwing an exception
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
22
Exception Handling (continued)
• Two fundamental types of errors:
– Result from inability of program to obtain required
resource
– Result from flawed code
• Checked exception
– Java checks that exceptions will be handled
– Program must throw or handle exception
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
23
Exception Handling (continued)
• Unchecked exception
– Java compiler does not check for handling code
– Error can always be prevented by programming
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
24
Exception Handling (continued)
Figure 4.4: Exception Handling Terminology
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
25
Exception Handling (continued)
try
{
// one or more statements
}
catch (exceptionName argument)
{
// one or more statements
}
finally
{
// one or more statements
}
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
26
Exception Handling (continued)
• try
– Identifies start of exception handling block of code
– Must be followed by one or more catch blocks
• catch
– Exception handler code
• finally
– Default set of instructions always executed whether
or not any exception occurred
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
27
Creating a Class Library
• Java provides extensive set of tested and reliable
classes
– Increases with introduction of each new version
• Professional programmers create and share own
libraries of classes
– Once they are tested
– Can be reused in other programs
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
28
Formatted Output
• Display of both integer and floating-point numbers
can be controlled by Java-supplied format()
method
– In class java.text.DecimalFormat
– Especially useful in printing columns with numbers
– Example:
• DecimalFormat num = new
DecimalFormat("000");
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
29
Formatted Output (continued)
• Required components for formatted output:
– Import statement for java.text package of
classes
– Statement within main() method that uses new
operator to create desired format string
– format() method call that applies format string
to numerical value
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
30
Formatted Output (continued)
Table 4.5: Symbols for User-Defined Format Strings
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
31
Formatted Output (continued)
Table 4.6: Examples of Numerical Formats
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
32
Formatted Output using printf
• Method of PrintStream class
• Syntax:
– printf(control string, arguments)
• Example:
– printf("The value of 6 plus 15 is %d%n",
6 + 15);
• Conversion control sequence
– Begins with % symbol
– Ends with conversion character
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
33
Formatted Output using printf
(continued)
Table 4.7: Common Conversion Sequences
for printf
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
34
Width and Precision Specifiers
• Optional specifications for numbers:
– Field width
– Precision
– Example:
• System.out.printf("|%10.3f|",
25.67);
– Width: 10
– Precision: 3
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
35
Width and Precision Specifiers
(continued)
Table 4.8: Effect of Field Width and Precision
Specifiers
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
36
Flags
• Justification
– Normally right-justified for numbers
– Use – flag to left-justify
• Explicit sign display
– Normally displayed only for negative numbers
– Use + flag to display for all numbers
• printf format
– %[flags] [width] [precision] conversionCharacter
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
37
Mathematical Methods
• Java provides standard preprogrammed methods
within class named Math
– Methods are static and public
• Each Math class method is called by:
–
–
–
–
Listing name of class
A period
Method’s name
Passing data within parentheses following
method’s name
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
38
Mathematical Methods (continued)
Table 4.9: Java’s Math Class Methods
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
39
Mathematical Methods (continued)
Figure 4.17: Using and passing data to a Math
class method
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
40
Casts
• Java provides for explicit user-specified type
conversions
• Use cast operator
– Unary operator
– Syntax:
• (dataType) expression
– Example:
• (int) (a * b)
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
41
Conversion Methods
• Routines for converting string to primitive type
and primitive type to string
• Referred to as wrapper classes
– Class structure wrapped around built-in:
•
•
•
•
integer
long
float
double
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
42
Conversion Methods (continued)
Table 4.11: Wrapper Class Conversion Routines
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
43
Conversion Methods (continued)
Figure 4.18: Conversions using a wrapper
class method
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
44
Common Programming Errors
• Forgetting to precede mathematical method with
class name Math and period
• Not understanding difference between writing
program for personal use and one intended for
someone else’s use
• Being unwilling to test program in depth that is to
be used by people other than yourself
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
45
Summary
• Input from keyboard accomplished using
readLine() method
– Must create InputStreamReader and
BufferedReader
• Input dialog box method used for data input
– From class JOptionPane
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
46
Summary (continued)
• Exception
– Error condition that occurs when program running
– Notification of exception immediately sent to Java
Virtual Machine for processing
• Java provides Math class
– Contains methods for mathematical computations
• Java String class provides methods for
converting strings into primitive numerical types
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
47