cs 46b: introduction to data structures june 9 class meeting department of computer science san jose...

41
CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak www.cs.sjsu.edu/~mak

Upload: edward-sutton

Post on 17-Jan-2016

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

CS 46B: Introduction to Data StructuresJune 9 Class Meeting

Department of Computer ScienceSan Jose State University

Summer 2015Instructor: Ron Mak

www.cs.sjsu.edu/~mak

Page 2: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

2

Quiz 6 June 11

Take “Quiz 6 June 11” in Canvas before the start of Thursday’s class.

Page 3: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

3

A Class Hierarchy Puzzle

Animal

Lion Dog Piranha Goldfish Parrot Hummingbird

Mammal Fish Bird

Suppose we want to add the category HouseholdPet. Do we make it a superclass? Where does it belong in this class hierarchy?

What if we also want to add the category Biter? Java allows a class to inherit from at most one superclass. No “multiple inheritance”

Page 4: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

4

A Class Hierarchy Puzzle, cont’d

Make HouseholdPet and Biter Java interfaces. A Java class can implement multiple interfaces.

Animal

Mammal Fish Bird

Lion Dog Piranha Goldfish Parrot Hummingbird

«interface»HouseholdPet

«interface»Biter

Page 5: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

5

Clicker Question June 9 #1

Suppose we define

Then which of the following is true?a. Method feed(Food f) is automatically private in the classes

that don’t implement interface HouseholdPet.

b. Method feed(Food f) is automatically public in the classes that do implement interface HouseholdPet.

c. We don’t need to implement method feed(Food f) in the classes that also implement interface Biter.

d. A class cannot implement both interfaces HouseholdPet and Biter.

public interface HouseholdPet{ void feed(Food f);}

Page 6: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

6

Java Subclass

If a class C is a subclass of superclass S, then C “is a” S: Dog is a Mammal Dog is an Animal

Animal

Mammal Fish Bird

Lion Dog Piranha Goldfish Parrot Hummingbird

Page 7: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

7

Java Interface

If a class C implements interface N, then C “is a” N: Dog is a HouseholdPet Dog is a Biter

Animal

Mammal Fish Bird

Lion Dog Piranha Goldfish Parrot Hummingbird

«interface»HouseholdPet

«interface»Biter

Page 8: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

8

Java instanceof Operator

If the value of variable x is of type Dog, then the following conditionals are all true:

x instanceof Dog x instanceof Mammal x instanceof Animal x instanceof HouseholdPet x instanceof Biter

Page 9: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

9

Feed Our Pets

How we find and feed all our pets that are in array animals?

public interface HouseholdPet{ void feed(Food f);}

for (int i = 0; i < animals.length; i++) { if ((animals[i] != null) && (animals[i] instanceof HouseholdPet)) { HouseholdPet pet = (HouseholdPet) animals[i]; Food f = new Food(); pet.feed(f); }}

Page 10: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

10

Feed Our Pets, cont’d

Instead of:

you can write:

HouseholdPet pet = (HouseholdPet) animals[i];pet.feed(f);

((HouseholdPet) animals[i]).feed(f);

The first way may be easier to write and read!

Page 11: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

11

Marker Interfaces

What if an interface type doesn’t declare anything? Suppose

public interface Biter{ // nothing!}

A marker interface is an empty interface that serves to “tag” the classes that implement it.

Use the instanceof operator to see which objects are from a tagged class.

Page 12: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

12

Avoid Biters!

Example of how to use a marker interface:

for (int i = 0; i < animals.length; i++) { if ((animals[i] != null) && (animals[i] instanceof Biter)) { // Code that does something // with animals that are biters. // // The code can’t call any // Biter methods because // there aren’t any. }}

Animal animals[];

Page 13: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

13

Java Interface Constants

An interface type cannot contain instance variables. Only a class type can have instance variables.

If an interface type definition declares any variables, they are automatically made public static final In other words, they’re constants. Any class that implements the interface shares the constants.

public interface HouseholdPet{ int VET_VISTS = 2; // visits per year to the vet ...}

Page 14: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

14

Objects and Interfaces

If class C implements interface N, then objects of class C can be assigned to variables of the interface type N.

public class Dog implements HouseholdPet{ ...}

HouseholdPet pet = new Dog(...);

Implements theHouseholdPet

interface

Interfacetype

Page 15: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

15

Objects and Interfaces, cont’d

The type of an object is never an interface type.

The type of a variable can be an interface type. The value of such a variable is a reference

to an object whose class implements the interface type.

public class Dog implements HouseholdPet{ ...}

HouseholdPet pet = new Dog(...);

Page 16: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

16

Break

Page 17: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

17

Reading and Writing Text Files

Most programs need to read input data and write output results.

We will look at how to read input data and write results in the form of text files.

The Scanner class is the most convenient way to read data from a text file.

The PrintWriter class is the most convenient way to write results to a text file.

Page 18: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

18

Create a Scanner Object

The constructor for the Scanner classcan have a reference to a File object as its argument:

Or:

The Scanner class lives in the java.util package, so you must import it:

File inputFile = new File("myinput.txt");Scanner in = new Scanner(inputFile);

Scanner in = new Scanner(new File("myinput.txt"));

import java.util.Scanner;

Page 19: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

19

Create a PrintWriter Object

The constructor for the PrintWriter class can have either a reference to a File object as its argument, or just the name of the output file:

The PrintWriter class lives in the java.io package, so you must import it:

PrintWriter out = new PrintWriter("myoutput.txt");

import java.io.PrintWriter;

Page 20: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

20

Create a PrintWriter Object, cont’d

What happens if the output file already exists? The file is completely overwritten with new contents.

What happens if the output file doesn’t already exist? A new output file is automatically created.

Page 21: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

21

Close the Input and Output Files

When your program is done with an input or an output file, it should close it:

If you don’t close an output file, the last part of your output may not make it into the file.

in.close(); // close the Scanner input fileout.close(); // close the PrintWriter output file

Page 22: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

22

Clicker Question June 9 #2

Consider the statement

a. This is a runtime error because the Scanner constructor expects a reference to a file object.

b. This is a compile-time error because the Scanner constructor expects a reference to a file object.

c. This is acceptable because your program will read from an input file named myinput.txt.

d. This is acceptable because your program will read from the string "myinput.txt".

Scanner in = new Scanner("myinput.txt");

Page 23: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

23

Read Words

The Scanner class’s hasNext() method returns true if there is a word to read next from the input; otherwise, it returns false.

The Scanner class’s next() method reads the next word from the input and returns it as a string.

Page 24: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

24

Read Words, cont’d

How do you read one word after anotherfrom an input text file? Suppose variable in is a reference

to a Scanner object:

How does this loop work?

while (in.hasNext()) { String word = in.next(); System.out.println(word);}

Page 25: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

25

Read Words, cont’d

If the input file contains

What is the output?

while (in.hasNext()) { String word = in.next(); System.out.println(word);}

Mary had a little lamb

Maryhadalittlelamb

Page 26: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

26

Read Words, cont’d

Java considers a word to be any consecutive sequence of characters that is not “white space”. White space includes any spaces, tabs,

and newline characters.

So if the input file contains instead

the output will beMary had 12 little #%@&!! lambs.

Maryhad12little#%@&!!lambs. Why?

Page 27: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

27

Read Words, cont’d

You can tell your Scanner object to only read words and discard anything else.

Tell it that any character that is not a letter (upper and lower case) is a “delimiter”. A delimiter is a character that separates one word

from another. What are word delimiters by default?

spaces, tabs, and newline characters

in.useDelimiter("[^A-Za-z]+");

A “regular expression” that says “one or more characters that is not a letter”.

Page 28: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

28

Read Characters

If you want to read a text file one character at a time, set the delimiter to an empty string:

Then in.next() will read the next character, but it will still return it as a string. How to get the character out of the string?

in.useDelimiter("");

while (in.hasNext()) { char ch = in.next().charAt(0); /* do something with ch */}

Page 29: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

29

Classify Characters

Each of the following boolean methods takes a character as an argument.

Typo: It should beisWhitespace(lower-case s).

Page 30: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

30

Read Lines

The Scanner class’s hasNextLine() method returns true if there is a line to read next from the input; otherwise, it returns false.

The Scanner class’s nextLine() method reads the next line from the input and returns it as a string.

Page 31: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

31

Read Lines, cont’d

How do you read one line after anotherfrom an input text file? Suppose variable in is a reference

to a Scanner object:

How does this loop work?

while (in.hasNextLine()) { String line = in.nextLine(); System.out.println(line);}

Page 32: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

32

Read Numbers

The Scanner class has methods to read numbers, including: hasNextInt() and nextInt() hasNextLong() and nextLong() hasNextDouble() and nextDouble()

Page 33: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

33

Read Numbers, cont’d

Note that if a number is the last item in an input line, methods nextInt(), nextLong(), and nextDouble() will not read the following newline character.

Therefore, a subsequent call to nextLine() will read an empty string.

So you will need yet another call to nextLine() to read the next input line.

Page 34: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

34

Handle I/O Errors

Examples of runtime I/O errors: Attempt to read a file that doesn’t exist. Attempt to read a number from an input text file

but there isn’t a number.

At run time, Java will detect I/O errors.

It is your program’s responsibility to handle the errors. What should your program do

when an I/O error occurs?

Page 35: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

35

Introduction to Exception Handling

Java exception handling is a flexible means of transferring runtime control: From the point an exception (error) is detected To special code to handle (deal with) the error.

try { /* code that can cause an exception, such as an attempt to read a nonexistent file. */}catch (FileNotFoundException ex) { /* code to handle the exception, such as writing an error message. */}

Page 36: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

36

Introduction to Exception Handling, cont’d

When a statement inside a try block causes an exception, your program immediately branches to the catch block.

After executing the catch block, your program continues to the next statement. It does not resume executing the try block.

try { ...}catch (SomeException ex) { ...}

The exception variable excontains useful information aboutthe exception that just occurred.

Page 37: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

37

FileNotFoundException Handler Example

public int countLines(){ int count = 0; Scanner in = null; try { in = new Scanner(inputFile); while (in.hasNextLine()) { in.nextLine(); ++count; } } catch (FileNotFoundException ex) { ex.printStackTrace(); } return count;}

Page 38: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

38

The finally Clause

Add a finally block to a try-catch statement for code that should be executed after the try block, whether or not an exception occurred.

try { in = new Scanner(inputFile); ...}catch (FileNotFoundException ex) { ex.printStackTrace();}finally { if (in != null) in.close();}

No matter whether the try block executed normally,or an exception occurred and the catch block executed,we will always close the input file.

Why do we need to checkwhether in is null?

Page 39: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

39

Homework #2

Write a Java program that will read Lincoln’s Gettysburg Address from a text file.

Count and print how many lines, words, and characters are in the text file. Just use the default word delimiters.

Calculate and print what percentage of the file’s characters are digits lower-case letters upper-case letters

white-space characters other characters

Page 40: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

40

Homework #2, cont’d

Draft: Due Wednesday, June 10 at 11:59 PM Just count and print the number of

lines, words, and characters. URL: http://codecheck.it/codecheck/files/

1506091032cjhe4tuyws7nwgo420hi8tkw8

Final: Due Friday, June 12 at 11:59 PM Also calculate and print the percentages. URL: http://codecheck.it/codecheck/files/

1506091036ay0zb7ctd13x92r8zy4xs7h7y

Canvas:Homework 2 Draft

Canvas:Homework 2 Final

Page 41: CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak mak

Computer Science Dept.Summer 2015: June 9

CS 46B: Introduction to Data Structures© R. Mak

41

Homework #2, cont’d

Input file GettysburgAddress.txt: http://www.cs.sjsu.edu/~mak/CS46B/assignments/2/GettysburgAddress.txt

Your solution must Use the Scanner class for the input file. Always close an open input file. Catch and handle runtime I/O errors.

For this assignment, to count lines, words, and characters, it’s probably easiest to open, read, and close the input file three times.