Chapter 4: Input and Formatting Class Methods

41
Chapter 4: Input and Formatting Class Methods Object-Oriented Program Development Using Java: A Class- Centered Approach

description

Chapter 4: Input and Formatting Class Methods. Object-Oriented Program Development Using Java: A Class-Centered Approach. Objectives. Interactive Keyboard Input Interactive Dialog Input Creating a Class Library Formatted Output Mathematical Methods Common Programming Errors. - PowerPoint PPT Presentation

Transcript of Chapter 4: Input and Formatting Class Methods

Page 1: Chapter 4:  Input and Formatting Class Methods

Chapter 4: Input and Formatting

Class MethodsObject-Oriented Program Development Using Java:

A Class-Centered Approach

Page 2: Chapter 4:  Input and Formatting Class Methods

2

Objectives

• Interactive Keyboard Input

• Interactive Dialog Input

• Creating a Class Library

• Formatted Output

• Mathematical Methods

• Common Programming Errors

Page 3: Chapter 4:  Input and Formatting Class Methods

3

Interactive Keyboard Input• Interactive data is entered:

– By a user at the keyboard– Via a graphical user interface (GUI)– From a file

• Data can be entered into a program while it is running using System.in object

• Stream objects:– Called streams for short– Transmit data as stream of individual data bytes

Page 4: Chapter 4:  Input and Formatting Class Methods

4

Interactive Keyboard Input (continued)

• End-of-file (EOF) marker:– Special end-of-data value

– Numerical value that cannot be converted into a legitimate character value

• If you would like to read an entire line at once:– Use supporting classes:

• InputStreamReader

• BufferedReader

Page 5: Chapter 4:  Input and Formatting Class Methods

5

Page 6: Chapter 4:  Input and Formatting Class Methods

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);

Page 7: Chapter 4:  Input and Formatting Class Methods

7

Interactive Keyboard Input (continued)

• BufferedReader:– Automatically constructs a string from character values

provided by the InputStreamReader object

– BufferedReader br = new BufferedReader(isr);

• A display prompt asks the user to enter data

• Calling readLine() puts system in wait state until the user types data

Page 8: Chapter 4:  Input and Formatting Class Methods

8

Page 9: Chapter 4:  Input and Formatting Class Methods

9

Page 10: Chapter 4:  Input and Formatting Class Methods

10

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

Page 11: Chapter 4:  Input and Formatting Class Methods

11

Page 12: Chapter 4:  Input and Formatting Class Methods

12

The Scanner Class• Introduced with Java 5.0• provides simpler method of reading numerical input• Replaces

BufferedReader br = newBufferedReader (new InputStreamReader (System.in);

String s1 = br.readLine();double num1 = Double.parseDouble(s1);with Scanner sc = new Scanner(System.in);double num1 = sc.nextDouble();

Page 13: Chapter 4:  Input and Formatting Class Methods

import java.util.*; // needed to access Scanner classpublic class MultiplyNumbers2{ public static void main (String[] args) throws Exception { double num1, num2, product;

Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); num1 = sc.nextDouble(); // reads in and converts number to double System.out.print("Great! Now enter another number: "); num2 = sc.nextDouble(); product = num1 * num2; System.out.println(num1 + " times " + num2 + " is " + product);

sc.close(); }}

Page 14: Chapter 4:  Input and Formatting Class Methods

14

Commonly Used Scanner Input Methods

See methods and description on page 189note especially

– nextBoolean( )– nextFloat( )– nextInt( )

• Note also that the scanner class scans tokens automatically

Page 15: Chapter 4:  Input and Formatting Class Methods

15

Interactive Dialog Inputpublic class SampleInputDialog{ public static void main (String[] args) { String s1, s2; double num1, num2, average; s1 = JOptionPane.showInputDialog("Enter a number:"); num1 = Double.parseDouble(s1); s2 = JOptionPane.showInputDialog("Great! Now enter another number:"); num2 = Double.parseDouble(s2); average = (num1 + num2)/2.0; JOptionPane.showMessageDialog(null, "The average of " + num1 + " and " + num2 + " is " + average, "QuickTest Program 4.3", JOptionPane.INFORMATION_MESSAGE); System.exit(0); }}

Page 16: Chapter 4:  Input and Formatting Class Methods

16

A First Look at User-Input Validation

• A well-constructed program:

– Validates user input

– Does not crash due to unexpected input

• A crash is program termination caused by an unexpected error

Page 17: Chapter 4:  Input and Formatting Class Methods

17

Page 18: Chapter 4:  Input and Formatting Class Methods

18

User-Input Validation

• Consists of:

– Validating entered data either during or immediately after data have been entered

– Providing the user with a way of reentering any invalid data

• To handle invalid input, provide error processing code

Page 19: Chapter 4:  Input and Formatting Class Methods

19

Dealing with Exceptions

• To throw error up to operating system, use reserved word throws with error name

Page 20: Chapter 4:  Input and Formatting Class Methods

20

Interactive Dialog Input

• GUI method of entering user data:– Method named showInputDialog()– In JOptionPane class– Creates dialog box that permits user to enter string at

terminal• Syntax:

– JOptionPane.showInputDialog(string);• Example:

– s = JOptionPane.showInputDialog("Enter a number:");

Page 21: Chapter 4:  Input and Formatting Class Methods

21

Page 22: Chapter 4:  Input and Formatting Class Methods

22

Exception Handling

• Error handling in Java:– Different from other high-level languages

• Exception handling:– Error occurs while a method is running– Method creates an object that contains information

about the error– Object immediately passed to Java Virtual Machine– JVM attempts to locate code to handle exception– Called throwing an exception

Page 23: Chapter 4:  Input and Formatting Class Methods

23

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

Page 24: Chapter 4:  Input and Formatting Class Methods

24

Page 25: Chapter 4:  Input and Formatting Class Methods

25

Exception Handling Syntaxtry{

// one or more statements}catch (exceptionName argument){

// one or more statements}finally{

// one or more statements}

Page 26: Chapter 4:  Input and Formatting Class Methods

26

Exception Handling Syntax (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

Page 27: Chapter 4:  Input and Formatting Class Methods

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, they can be reused in other programs

Page 28: Chapter 4:  Input and Formatting Class Methods

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");

Page 29: Chapter 4:  Input and Formatting Class Methods

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

Page 30: Chapter 4:  Input and Formatting Class Methods

30

Page 31: Chapter 4:  Input and Formatting Class Methods

31

Page 32: Chapter 4:  Input and Formatting Class Methods

32

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

Page 33: Chapter 4:  Input and Formatting Class Methods

33

Page 34: Chapter 4:  Input and Formatting Class Methods

34

Page 35: Chapter 4:  Input and Formatting Class Methods

35

Casts

• Java provides for explicit user-specified type conversions

• Use cast operator:– Unary operator

– Syntax:• (dataType) expression

– Example:• (int) (a * b)

Page 36: Chapter 4:  Input and Formatting Class Methods

36

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

Page 37: Chapter 4:  Input and Formatting Class Methods

37

Page 38: Chapter 4:  Input and Formatting Class Methods

38

Page 39: Chapter 4:  Input and Formatting Class Methods

39

Common Programming Errors

• Forgetting to precede mathematical methods 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

Page 40: Chapter 4:  Input and Formatting Class Methods

40

Summary• Input from the keyboard can be accomplished

using the readLine() method

• Input dialog box method is used for data input

– From class JOptionPane

• Exception is an error condition that occurs when program is running

– Notification of exception is immediately sent to Java Virtual Machine for processing

Page 41: Chapter 4:  Input and Formatting Class Methods

41

Summary (continued)

• Java provides the Math class

– Contains methods for mathematical computations

• Java String class provides methods for converting strings into primitive numerical types