• Tidak ada hasil yang ditemukan

PPT Slide 1

N/A
N/A
Protected

Academic year: 2023

Membagikan "PPT Slide 1"

Copied!
82
0
0

Teks penuh

(1)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Data Structures for Java Data Structures for Java

William H. Ford William H. Ford William R. Topp William R. Topp

Chapter 2 Chapter 2

Class Relationships Class Relationships

Bret Ford

© 2005, Prentice Hall

(2)

Wrapper Classes Wrapper Classes

 Convert a value of primitive type to an Convert a value of primitive type to an object.

object.

 Supply methods to access and display the Supply methods to access and display the value.

value.

 Wrapper classes include Integer, Double, Wrapper classes include Integer, Double, and Boolean.

and Boolean.

(3)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Comparing Integer Objects Comparing Integer Objects

 Compare primitive values using ==, <, Compare primitive values using ==, <,

<=, >, >=, etc.

<=, >, >=, etc.

 Use equals() and compareTo() for Use equals() and compareTo() for comparing objects.

comparing objects.

Example: Compare Integer objects objA and objB.

Integer objA = new Integer(35), objB = new Integer(50);

int t = objA.compareTo(objB); // t < 0 since 35 < 50

boolean b = objB.equals(new Integer("35")); // b is true //assign to objMax the larger of the two Integer objects.

Integer objMin = (objA.compareTo(objB) > 0) ? objA : objB;

(4)

Wrapper Classes Integer, Character Wrapper Classes Integer, Character

and Double

and Double

(5)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Static Wrapper Class Members Static Wrapper Class Members

 Integer.MIN_VALUE and Integer.MIN_VALUE and

Integer.MAX_VALUE are the minimum and Integer.MAX_VALUE are the minimum and

maximum integer values maximum integer values

 Double has similar constants. Double has similar constants.

 Methods such as the Integer parseInt() Methods such as the Integer parseInt() method convert a numeric string to the method convert a numeric string to the

corresponding primitive value.

corresponding primitive value.

 toString() provides a string representation toString() provides a string representation for a primitive type.

for a primitive type.

(6)

Character Handling Character Handling

Character is a wrapper class for the primitive Character is a wrapper class for the primitive type char.

type char.

Classifying a character Classifying a character

public static boolean isLetter(char ch);

public static boolean isLetter(char ch);

public static boolean isDigit(char ch);

public static boolean isDigit(char ch);

public static boolean isWhitespace(char ch);

public static boolean isWhitespace(char ch);

Testing and Modifying Case of a Character Testing and Modifying Case of a Character

public static boolean isUpperCase(char ch);

public static boolean isUpperCase(char ch);

public static boolean isLowerCase(char ch);

public static boolean isLowerCase(char ch);

public static char toUpperCase(char ch);

public static char toUpperCase(char ch);

public static char toLowerCase(char ch);

public static char toLowerCase(char ch);

(7)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Autoboxing and Autoboxing and

Auto-unboxing Auto-unboxing

 Autoboxing automatically converts a Autoboxing automatically converts a

primitive type to its associated wrapper primitive type to its associated wrapper

type.

type.

Example: Example:

Integer[] arr = {5, 3, 2, 9, 35};Integer[] arr = {5, 3, 2, 9, 35};

 Auto-unboxing automatically converts Auto-unboxing automatically converts from a wrapper type to the equivalent from a wrapper type to the equivalent

primitive type.

primitive type.

Example: Example:

int n = arr[1];int n = arr[1];

(8)

Object Composition Object Composition

 Class (client class) contains one or more Class (client class) contains one or more objects of another class (supplier class).

objects of another class (supplier class).

 Termed the “has-a” relationship. Termed the “has-a” relationship.

(9)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

TimeCard Class TimeCard Class

 Maintains data for hourly workers. Maintains data for hourly workers.

private String workerID;private String workerID;

private double payrate;

private double payrate;

private Time24 punchInTime, punchOutTime;

private Time24 punchInTime, punchOutTime;

(10)

public TimeCard(String workerID, double payrate, int punchInHour, int punchInMinute) {

// initialize workerID and payrate this.workerID = workerID;

this.payrate = payrate;

// create Time24 object by calling // constructor Time24(hour,minute) punchInTime = new Time24(punchInHour, punchInMinute);

// create Time24 object by calling // default constructor Time24()

punchOutTime = new Time24();

}

TimeCard Constructor

TimeCard Constructor

(11)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

payworker() payworker()

public String payWorker(int punchOutHour, int punchOutMinute) {

// local variables for time // worked and hours worked Time24 timeWorked;

// timeWorked converted to hours double hoursWorked;

// numeric format object for // hours worked and pay

DecimalFormat fmt =

new DecimalFormat("0.00");

// update punchOutTime by calling setTime() punchOutTime.setTime(punchOutHour,

punchOutMinute);

(12)

payworker() (continued) payworker() (continued)

// evaluate time worked with Time24 // interval() method

timeWorked =

punchInTime.interval(punchOutTime);

// hoursWorked is timeWorked as // fractional part of an hour

hoursWorked = timeWorked.getHour() +

timeWorked.getMinute()/60.0;

(13)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

// return formatted string return "Worker: " + workerID + "\n" +

"Start time: " + punchInTime + "End time: " +

punchOutTime + "\n" + "Total time: " +

fmt.format(hoursWorked) + " hours" + "\n" +

"At $" + fmt.format(payrate) + " per hour, pay is $" +

fmt.format(payrate*hoursWorked);

}

payworker() (concluded)

payworker() (concluded)

(14)

UML for the TimeCard Class

UML for the TimeCard Class

(15)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Inheritance in Java Inheritance in Java

 An “is a” relationship that involves sharing An “is a” relationship that involves sharing of attributes and methods among classes.

of attributes and methods among classes.

 A superclass defines a common set of A superclass defines a common set of attributes and operations.

attributes and operations.

 A subclass extends the resources in a A subclass extends the resources in a superclass by adding its own data and superclass by adding its own data and

methods.

methods.

(16)

Inheritance Hierarchy Tree

Inheritance Hierarchy Tree

(17)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Visibility for Members in an Visibility for Members in an

Inheritance Hierarchy Inheritance Hierarchy

 Private members accessible only within a Private members accessible only within a particular class.

particular class.

 Protected members are accessible by Protected members are accessible by defining class and all subclasses.

defining class and all subclasses.

 Public members are accessible by the Public members are accessible by the defining class, all subclasses, and any defining class, all subclasses, and any

instance of the class.

instance of the class.

(18)

Scope Rules in Inheritance Scope Rules in Inheritance

Hierarchies

Hierarchies

(19)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Employee Inheritance Employee Inheritance

Hierarchy Hierarchy

 Superclass Employee specifies name and Superclass Employee specifies name and Social Security Number and associated Social Security Number and associated

methods.

methods.

 The subclasses SalaryEmployee and The subclasses SalaryEmployee and

HourlyEmployee inherit (extend) Employee HourlyEmployee inherit (extend) Employee

and add data and methods for handling and add data and methods for handling

salaried workers and hourly workers.

salaried workers and hourly workers.

(20)

class Employee {

// instance variables are accessible by // subclass methods

protected String empName;

protected String empSSN;

// create an object with initial values // empName and empSSN

public Employee(String empName, String empSSN) {

this.empName = empName;

this.empSSN = empSSN;

}

// update the employee name

public void setName(String empName) { this.empName = empName; }

Employee Class

Employee Class

(21)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

// returns a formatted string to display // employee information

public String toString()

{ return "Name: " + empName + '\n' + "SS#: " + empSSN; }

// method is declared in this // class for polymorphism

public String payrollCheck() { return ""; }

}

Employee Class (concluded)

Employee Class (concluded)

(22)

SalaryEmployee Subclass SalaryEmployee Subclass

 SalaryEmployee class extends Employee SalaryEmployee class extends Employee and adds a salrary instance variable along and adds a salrary instance variable along

with methods that access the salary.

with methods that access the salary.

(23)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

SalaryEmployee API

SalaryEmployee API

(24)

Keyword super Keyword super

 Use super(args) in a subclass constructor Use super(args) in a subclass constructor to call the superclass constructor. Must be to call the superclass constructor. Must be

the first statement in the constructor.

the first statement in the constructor.

 For methods with the same name in the For methods with the same name in the subclass and the superclass, call the

subclass and the superclass, call the superclass method using the form

superclass method using the form super.method(args)

super.method(args)

(25)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

public SalaryEmployee(String empName, String empSSN, double salary) {

// call the Employee

// superclass constructor super(empName, empSSN);

this.salary = salary;

}

SalaryEmployee Constructor

SalaryEmployee Constructor

(26)

public String toString() {

DecimalFormat fmt =

new DecimalFormat("#.00");

return super.toString() + '\n' + "Status: Salary" + '\n' +

"Salary: $" + fmt.format(salary);

}

SalaryEmployee toString()

SalaryEmployee toString()

(27)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

HourlyEmployee Subclass HourlyEmployee Subclass

 Declares private instance variables Declares private instance variables

hourlyPayhourlyPay

and and

hoursWorkedhoursWorked

of type double of type double

(28)

UML for the UML for the

Employee Hierarchy

Employee Hierarchy

(29)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Assignment in an Inheritance Assignment in an Inheritance

Hierarchy Hierarchy

 Can assign any subclass reference to a Can assign any subclass reference to a superclass reference.

superclass reference.

Employee emp;Employee emp;

SalaryEmployee sEmp = SalaryEmployee sEmp =

new SalaryEmployee(“Morris, Mike”, “569-34-0382”, new SalaryEmployee(“Morris, Mike”, “569-34-0382”, 1250.00);

1250.00);

emp = sEmp;

emp = sEmp;

(30)

Assignment in an Inheritance Assignment in an Inheritance

Hierarchy (concluded) Hierarchy (concluded)

 Superclass variable that references a Superclass variable that references a subclass object can be used to call any subclass object can be used to call any

public method in the superclass.

public method in the superclass.

 May not be used to call a method defined May not be used to call a method defined only in the subclass.

only in the subclass.

// invalid! setSalary() is not defined in Employee emp.setSalary(1500.00);

// valid! uses reference emp to call an Employee method emp.setName("Morris, Michael");

(31)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Static Binding Static Binding

 Static binding associates a method with Static binding associates a method with the class type of a reference variable.

the class type of a reference variable.

Example:

Example:

emp.setName(“Harrison, Pamela”),emp.setName(“Harrison, Pamela”), sEmp.setSalary(1500.0)

sEmp.setSalary(1500.0)

(32)

Overriding Methods Overriding Methods

 When the superclass and the subclass When the superclass and the subclass have methods with the same signature, have methods with the same signature,

we say that the subclass method we say that the subclass method

“overrides” the superclass method.

“overrides” the superclass method.

// emp = sEmp sets emp to point at sEmp ("Michael Morris").

// the runtime system executes payrollCheck SalaryEmployee System.out.println(emp.payrollCheck());

Output:

Pay Morris, Mike (569-34-0382) $1250.00

(33)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Polymorphism Polymorphism

 When the superclass and one or more When the superclass and one or more

subclasses define methods with the same subclasses define methods with the same

signature, the runtime system executes signature, the runtime system executes

the subclass method under the following the subclass method under the following

conditions conditions

A subclass object is assigned to a superclass A subclass object is assigned to a superclass reference variable.

reference variable.

The method call uses the superclass reference The method call uses the superclass reference variable.

variable.

(34)

Polymorphism (concluded) Polymorphism (concluded)

 Rather than using static binding which Rather than using static binding which would associate the method with the would associate the method with the

superclass reference variable, the compiler superclass reference variable, the compiler

directs the runtime system to determine directs the runtime system to determine

the subclass type referenced by the the subclass type referenced by the

variable and then calls the corresponding variable and then calls the corresponding subclass method. This is dynamic binding subclass method. This is dynamic binding

since the association between reference since the association between reference

variable and method is established at variable and method is established at

runtime.

runtime.

(35)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Polymorphism Example Polymorphism Example

// declare a subclass object HourlyEmployee hEmp =

new HourlyEmployee("Holmes, Julie", "837-68-2198", 12.00, 30);

// assign subclass object hEmp to superclass // reference variable

emp = hEmp;

// create a pay check using polymorphism System.out.println(emp.payrollCheck());

Output:

Pay Holmes, Julie (837-68-2198) $360.00

(36)

Upcasting Upcasting

 Upcasting occurs when a subclass object Upcasting occurs when a subclass object reference is assigned to a superclass

reference is assigned to a superclass reference.

reference.

Superclass reference variable may call any Superclass reference variable may call any public method in the superclass and any public method in the superclass and any

public method in the subclass for which public method in the subclass for which

polymorphism applies.

polymorphism applies.

(37)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Downcasting Downcasting

 A superclass reference variable may not A superclass reference variable may not be used to call a method defined

be used to call a method defined

exclusively in a subclass. The programmer exclusively in a subclass. The programmer

must use a cast to chance the reference must use a cast to chance the reference

type of variable to that of the subclass.

type of variable to that of the subclass.

(38)

Downcasting Example Downcasting Example

SalaryEmployee sEmp =

new SalaryEmployee(“Bonner, Al”, “667-21-7128”

2500.0);

Employee emp;

Emp = sEmp;

((SalaryEmployee)emp).setSalary(3000.0);

(39)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

The instanceof Operator The instanceof Operator

 Sometimes the choice of an downcast Sometimes the choice of an downcast cannot be made until runtime. The

cannot be made until runtime. The instanceof operator allows the

instanceof operator allows the determination of subclass type.

determination of subclass type.

 The method payIncrease() provides a The method payIncrease() provides a good example of using the instanceof good example of using the instanceof

operator. Its first argument can be either operator. Its first argument can be either

a SalaryEmployee or an HourlyEmployee.

a SalaryEmployee or an HourlyEmployee.

// give employee a percentage pay increase of pct public void payIncrease(Employee emp, double pct)

(40)

public static void payIncrease(Employee emp, double pct) {

// use instanceof to determine the

// object type for emp if SalaryEmployee, // access and update salary

if (emp instanceof SalaryEmployee) ((SalaryEmployee)emp).setSalary(

(1.0 + pct) *

((SalaryEmployee)emp).getSalary());

else

((HourlyEmployee)emp).setHourlyPay(

(1.0 + pct) *

((HourlyEmployee)emp).getHourlyPay());

}

payIncrease()

payIncrease()

(41)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Abstract Classes Abstract Classes

 Define an abstract method in a class by Define an abstract method in a class by preceding the signature with the keyword preceding the signature with the keyword

abstract and replacing the method body abstract and replacing the method body

by “;”. Place the keyword abstract in the by “;”. Place the keyword abstract in the

class header.

class header.

abstract class ClassName {

// abstract class may contain data and concrete methods . . .

// abstract class must contain at least one abstract method abstract public returnType methodName(<parameters>);

}

(42)

Abstract Classes (concluded) Abstract Classes (concluded)

 Each subclass of an abstract class must Each subclass of an abstract class must

override all of the abstract methods in the override all of the abstract methods in the

superclass.

superclass.

 A program cannot create an instance of an A program cannot create an instance of an abstract class.

abstract class.

 Provides only resources for a subclass and Provides only resources for a subclass and method declarations that can be used with method declarations that can be used with

polymorphism.

polymorphism.

(43)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

The throw Statement The throw Statement

 An exception is an object that is created An exception is an object that is created within a method at a point where an error within a method at a point where an error

condition occurs.

condition occurs.

 Create the exception object in a throw Create the exception object in a throw statement that passes the object back statement that passes the object back

through a chain of method calls to a block through a chain of method calls to a block

of code designed to catch the exception of code designed to catch the exception

(an exception handler).

(an exception handler).

throw new ExceptionTypeException(errorMessage);

(44)

// throws IllegalArgumentException // object with the message

// "average(): invalid array"

public static double average(double[] arr) {

double sum = 0;

// if array is null or of length 0, throw // exception and exit

if (arr == null || arr.length == 0) throw new InvalidArgumentException(

"average(): Invalid array");

// preconditions satisfied; compute and // return the average

for (int i = 0; i < arr.length; i++) sum += arr[i];

return sum/arr.length;

average()

average()

(45)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Handling an Exception Handling an Exception

 The try statement is a block of code that The try statement is a block of code that may generate an exception.

may generate an exception.

 A catch block must immediately follow a A catch block must immediately follow a try block and serves as the exception

try block and serves as the exception handler.

handler.

Try-Catch Statements:

try {

<program statements>

}

catch (ExceptionTypeException e) {

<display error message>

< perform other tasks or exit the program>

}

(46)

Handling an Exception Handling an Exception

(concluded) (concluded)

 If no exception occurs, processing occurs If no exception occurs, processing occurs after the catch block.

after the catch block.

 If a statement in a try block causes an If a statement in a try block causes an exception, an immediate exit from the exception, an immediate exit from the

block occurs, and control passes to the block occurs, and control passes to the

catch block specified to handle the catch block specified to handle the

exception.

exception.

(47)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Try/Catch Block Example Try/Catch Block Example

public static void main(String[] args) {

// declare two array references;

double[] arrA = {2.5, 5.0, 7.2, 8.1}, arrB = null;

try {

// arrA is valid and average() // returns a value

// arrB is not valid (null) and // average() throws an exception System.out.println("Average is " + average(arrA));

System.out.println("Average is " + average(arrB));

}

(48)

Try/Catch Block Example Try/Catch Block Example

(concluded) (concluded)

catch (IllegalArgumentException e) {

System.out.println(e);

// exit the program System.exit(1);

} }

(49)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Finally Clause Finally Clause

 The finally clause defines a block of code The finally clause defines a block of code that always executes, no matter whether that always executes, no matter whether

the try block executes successfully or the try block executes successfully or

causes an exception.

causes an exception.

 Used typically to manage system Used typically to manage system resources, such as close files.

resources, such as close files.

try

{ ... }

catch (ExceptionTypeException e)

{ ... } finally { ... }

(50)

Error Propagation Error Propagation

 The exception handling mechanism may The exception handling mechanism may involve a chain of method calls with the involve a chain of method calls with the

exception occurring at some distant point exception occurring at some distant point

in the chain.

in the chain.

(51)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Java Exception Hierarchy

Java Exception Hierarchy

(52)

Standard Exceptions Standard Exceptions

ArithmeticException ArithmeticException

Thrown when an exceptional arithmetic condition has Thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero"

occurred. For example, an integer "divide by zero"

throws an instance of this class.

throws an instance of this class.

IllegalArgumentException IllegalArgumentException

Thrown to indicate that a method has been passed an Thrown to indicate that a method has been passed an illegal or inappropriate argument

illegal or inappropriate argument

IndexOutOfBoundsException IndexOutOfBoundsException

Thrown to indicate that an index of some sort (such Thrown to indicate that an index of some sort (such as an array, a string, or an ArrayList) is out of range.

as an array, a string, or an ArrayList) is out of range.

(53)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Standard Exceptions Standard Exceptions

(concluded) (concluded)

 NullPointerException NullPointerException

Thrown when an application attempts to use Thrown when an application attempts to use null in a case where an object is required

null in a case where an object is required

 UnsupportedOperationException UnsupportedOperationException

Thrown to indicate that the requested Thrown to indicate that the requested operation is not supported.

operation is not supported.

(54)

public static Time24 parseTime(String s) {

// tokens separated by space // or colon character

StringTokenizer stok =

new StringTokenizer(s, " :");

String timePeriod = null;

int hour, minute;

// get tokens and convert to // hour and minute

hour = Integer.parseInt(stok.nextToken());

minute = Integer.parseInt(stok.nextToken());

// create a Time24 object // as the return value

return new Time24(hour, minute);

}

parseTime()

parseTime()

(55)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Streams Streams

 I/O streams carry data. I/O streams carry data.

Text streams have character data such as an Text streams have character data such as an HTML file or a Java source file.

HTML file or a Java source file.

Binary streams have byte data that may Binary streams have byte data that may

represent a graphic or executable code, such represent a graphic or executable code, such

as a Java .class file.

as a Java .class file.

 A stream carries data from a source to a A stream carries data from a source to a destination such as a monitor or hard disk.

destination such as a monitor or hard disk.

(56)

Stream Sources and Stream Sources and

Destinations

Destinations

(57)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Types of Streams Types of Streams

 If data flows from a source into a If data flows from a source into a

program, it is called an input stream.

program, it is called an input stream.

 If data flows from a program to a If data flows from a program to a

destination, it is called an output stream.

destination, it is called an output stream.

 The basic stream classes are defined in The basic stream classes are defined in the package “java.io”.

the package “java.io”.

(58)

Console I/O Console I/O

 Allows a program to input data from the Allows a program to input data from the keyboard and display output in a console keyboard and display output in a console

window.

window.

 The three console streams: The three console streams:

System.in for character input (standard System.in for character input (standard input).

input).

System.out for character output (standard System.out for character output (standard output).

output).

System.err character output (standard error). System.err character output (standard error).

(59)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Console Output Examples Console Output Examples

 We are already familiar with console We are already familiar with console output.

output.

Example: Example:

System.out.print("Displayed in console window");

System.out.print("Displayed in console window");

System.err.println("Posting an error message");

System.err.println("Posting an error message");

(60)

File I/O File I/O

A file is a collection of data that is stored in A file is a collection of data that is stored in some medium such as a disk.

some medium such as a disk.

A file that can be viewed as a sequence of A file that can be viewed as a sequence of characters partitioned into lines is a text file.

characters partitioned into lines is a text file.

A text file can be listed on a console window or A text file can be listed on a console window or viewed with an editor.

viewed with an editor.

Nontext files are termed binary files. Nontext files are termed binary files.

Compressed data is stored in a binary file. Compressed data is stored in a binary file.

(61)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Text Input with Text Input with Reader Streams Reader Streams

 Text input derived from the abstract class Text input derived from the abstract class java.io.Reader which defines basic

java.io.Reader which defines basic character input methods.

character input methods.

 The java.io.FileReader class inputs data The java.io.FileReader class inputs data from a disk file.

from a disk file.

Example:

Example:

FileReader datIn =FileReader datIn =

new FileReader("testdata.dat");

new FileReader("testdata.dat");

(62)

Text Input with Text Input with

Reader Streams (concluded) Reader Streams (concluded)

 java.io.InputStream is a bridge from byte java.io.InputStream is a bridge from byte streams to character streams. It reads

streams to character streams. It reads bytes and decodes them into characters.

bytes and decodes them into characters.

 java.io.BufferedReader reads text from a java.io.BufferedReader reads text from a character-input stream, buffering

character-input stream, buffering

characters to provide for the efficient characters to provide for the efficient

reading of characters, arrays, and lines.

reading of characters, arrays, and lines.

Example:

Example:

BufferedReader keyBoard =BufferedReader keyBoard = new BufferedReader(

new BufferedReader(

new InputStreamReader(System.in));

new InputStreamReader(System.in));

(63)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

The Reader Hierarchy

The Reader Hierarchy

(64)

StringTokenizer StringTokenizer

 java.util.StringTokenizer has methods that java.util.StringTokenizer has methods that separate a string into tokens.

separate a string into tokens.

Example:

Example:

String str;

String str;

// tokens are blank and colon // tokens are blank and colon StringTokenizer stok =

StringTokenizer stok =

new StringTokenizer(str, " :");

new StringTokenizer(str, " :");

while (stok.hasMoreTokens()) while (stok.hasMoreTokens())

System.out.println(stok.nextToken());System.out.println(stok.nextToken());

(65)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

public static Time24 parseTime(String s) {

// tokens separated by space // or colon character

StringTokenizer stok =

new StringTokenizer(s, " :");

String timePeriod = null;

int hour, minute;

// get tokens and convert to // hour and minute

hour = Integer.parseInt(stok.nextToken());

minute = Integer.parseInt(stok.nextToken());

// create a Time24 object // as the return value

return new Time24(hour, minute);

}

parseTime()

parseTime()

(66)

Text Output with Text Output with

Writer Streams Writer Streams

 The abstract java.io.Writer class defines The abstract java.io.Writer class defines basic operations for inserting a character basic operations for inserting a character

or arrays of characters into a stream.

or arrays of characters into a stream.

 The class java.io.FileWriter creates objects The class java.io.FileWriter creates objects that are attached to a file on disk.

that are attached to a file on disk.

Example:

Example:

FileWriter dataOut = new FileWriter("output.dat");FileWriter dataOut = new FileWriter("output.dat");

(67)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Output with Print Statements Output with Print Statements

 The class java.io.PrintWriter wraps around The class java.io.PrintWriter wraps around a Writer object and outputs formatted

a Writer object and outputs formatted data.

data.

Example:

Example:

PrintWriter pw = new PrintWriter(PrintWriter pw = new PrintWriter(

new FileWriter("data.out"));

new FileWriter("data.out"));

int n = 5;

int n = 5;

pw.println("n = " + n);

pw.println("n = " + n);

(68)

Writer Inheritance Hierarchy

Writer Inheritance Hierarchy

(69)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Controlling the Controlling the

Output Stream Output Stream

 The method flush() directs the I/O system The method flush() directs the I/O system to copy all buffered data to the output

to copy all buffered data to the output stream.

stream.

 The method close() closes the stream and The method close() closes the stream and releases all resources associated with the releases all resources associated with the

stream.

stream.

(70)

The Scanner Class The Scanner Class

 A Scanner object partitions text from an A Scanner object partitions text from an input stream into tokens by means of its input stream into tokens by means of its

"next" methods.

"next" methods.

 Declare a Scanner object as follows: Declare a Scanner object as follows:

Scanner keyIn = new Scanner(System.in);Scanner keyIn = new Scanner(System.in);

Scanner fileIn = new Scanner(

Scanner fileIn = new Scanner(

new FileReader("demo.dat"));

new FileReader("demo.dat"));

(71)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Scanner Methods Scanner Methods

 String line = sc.nextLine(); // whole line String line = sc.nextLine(); // whole line

 int i = sc.nextInt(); // i = 17 int i = sc.nextInt(); // i = 17

 String str = sc.next(); // str = "deposit" String str = sc.next(); // str = "deposit"

 double x = sc.nextDouble(); // x = 450.75 double x = sc.nextDouble(); // x = 450.75

 boolean b = sc.nextBoolean(); // b = false boolean b = sc.nextBoolean(); // b = false

 char ch = sc.next().charAt(0); // ch = 'A' char ch = sc.next().charAt(0); // ch = 'A'

(72)

Testing for Testing for

Scanner Tokens Scanner Tokens

// loop reads tokens in the line while (sc.hasNext())

{

token = sc.next();

System.out.println("In loop next token = " + token);

}

Output:

In loop next token = 17

In loop next token = deposit In loop next token = 450.75 In loop next token = false In loop next token = A

(73)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

File Input using Scanner File Input using Scanner

A sports team creates the file "attendance.dat" to store

attendance data for home games during the season. The example uses the Scanner object dataIn and a loop to read the sequence of attendance values from the file and determine the total

attendance. The condition hasNextInt() returns false when all of the data has been read from the file.

// create an Scanner object attached to the file "attendance.dat"

Scanner dataIn = new Scanner(new FileReader("attendance.dat"));

int gameAtt, totalAtt = 0;

// the loop reads the integer game attendance until end-of-file while(dataIn.hasNextInt()) // loop iteration condition {

gameAtt = dataIn.nextInt(); // input next game attendance totalAtt += gameAtt; // add to the total

}

(74)

Scanner Class API

Scanner Class API

(75)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Scanner Class API Scanner Class API

continued

continued

(76)

Scanner Class API Scanner Class API

(concluded)

(concluded)

(77)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

import java.util.Scanner;

import java.io.*;

import java.text.DecimalFormat;

public class Program2_1 {

public static void main(String[] args) {

final double SALESTAX = 0.05;

// input streams for the keyboard and a file Scanner fileIn = null;

// input variables and pricing information String product;

int quantity;

double unitPrice, quantityPrice, tax, totalPrice;

char taxStatus;

Program 2.1

Program 2.1

(78)

// create formatted strings for // aligning output

DecimalFormat fmtA = new DecimalFormat("#"),

fmtB = new DecimalFormat("$#.00");

// open the file; catch exception // if file not found

// use regular expression as delimiter try

{

fileIn =

new Scanner(new FileReader("food.dat"));

fileIn.useDelimiter("[\t\n\r]+");

}

Program 2.1 (continued)

Program 2.1 (continued)

(79)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

catch (IOException ioe) {

System.err.println("Cannot open file " + "'food.dat'");

System.exit(1);

}

// header for listing output System.out.println("Product" + align("Quantity", 16) + align("Price", 10) + align("Total", 12));

Program 2.1 (continued)

Program 2.1 (continued)

(80)

// read to end of file; break // when no more tokens

while(fileIn.hasNext()) {

// input product/purchase input fields product = fileIn.next();

quantity = fileIn.nextInt();

unitPrice = fileIn.nextDouble();

taxStatus = fileIn.next().charAt(0);

// calculations and output

quantityPrice = unitPrice * quantity;

tax = (taxStatus == 'Y') ? quantityPrice *

SALESTAX : 0.0;

totalPrice = quantityPrice + tax;

Program 2.1 (continued)

Program 2.1 (continued)

(81)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

System.out.println(product +

align("", 15-product.length()) + align(fmtA.format(quantity), 6) + align(fmtB.format(unitPrice), 13) + align(fmtB.format(totalPrice),12) + ((taxStatus == 'Y') ? " *" : ""));

} }

// aligns string right justified // in a field of width n

public static String align(String str, int n) {

String alignStr = "";

for (int i = 1; i < n - str.length(); i++) alignStr += " ";

alignStr += str;

return alignStr;

} }

Program 2.1 (concluded)

Program 2.1 (concluded)

(82)

Input file ('food.dat') Soda 3 2.69 Y

Eggs 2 2.89 N Bread 3 2.49 N

Grapefruit 8 0.45 N Batteries 10 1.15 Y Bakery 1 14.75 N Run:

Product Quantity Price Total Fruit Punch 4 $2.69 $11.30 * Eggs 2 $2.89 $5.78 Rye Bread 3 $2.49 $7.47 Grapefruit 8 $.45 $3.60 AA Batteries 10 $1.15 $12.08 * Ice Cream 1 $3.75 $3.75

Program 2.1 Run

Program 2.1 Run

Referensi

Dokumen terkait

Setelah melihat analisis situasi di atas, dan menurut hasil observasi yang telah dilakukan pada Yayasan Peduli Anak Kuta, maka dapat dilihat permasalahan yang dihadapi oleh anaka-anak