Download CS 46B: Introduction to Data Structures

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

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

Document related concepts
no text concepts found
Transcript
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
Quiz 6 June 11

Take “Quiz 6 June 11” in Canvas before the
start of Thursday’s class.
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
2
A Class Hierarchy Puzzle
Animal
Mammal
Lion

Piranha
Bird
Goldfish
Parrot
Hummingbird
Suppose we want to add the category HouseholdPet.



Dog
Fish
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”
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
3
A Class Hierarchy Puzzle, cont’d
Animal
Mammal
Lion
Fish
Dog
Piranha
«interface»
HouseholdPet

Bird
Goldfish
Parrot
Hummingbird
«interface»
Biter
Make HouseholdPet and Biter Java interfaces.

A Java class can implement multiple interfaces.
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
4
Clicker Question June 9 #1

Suppose we define

Then which of the following is true?
a.
b.
c.
d.
public interface HouseholdPet
{
void feed(Food f);
}
Method feed(Food f) is automatically private in the classes
that don’t implement interface HouseholdPet.
Method feed(Food f) is automatically public in the classes
that do implement interface HouseholdPet.
We don’t need to implement method feed(Food f) in the
classes that also implement interface Biter.
A class cannot implement both interfaces HouseholdPet
and Biter.
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
5
Java Subclass
Animal
Mammal
Lion

Dog
Fish
Piranha
Bird
Goldfish
Parrot
Hummingbird
If a class C is a subclass of superclass S,
then C “is a” S:


Dog is a Mammal
Dog is an Animal
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
6
Java Interface
Animal
Mammal
Lion
Fish
Dog
Piranha
«interface»
HouseholdPet

Bird
Goldfish
Parrot
Hummingbird
«interface»
Biter
If a class C implements interface N, then C “is a” N:


Dog is a HouseholdPet
Dog is a Biter
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
7
Java instanceof Operator

If the value of variable x is of type Dog,
then the following conditionals are all true:





x
x
x
x
x
instanceof
instanceof
instanceof
instanceof
instanceof
Computer Science Dept.
Summer 2015: June 9
Dog
Mammal
Animal
HouseholdPet
Biter
CS 46B: Introduction to Data Structures
© R. Mak
8
Feed Our Pets
public interface HouseholdPet
{
void feed(Food f);
}

How we find and feed all our pets
that are in array animals?
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);
}
Computer Science Dept.
CS 46B: Introduction to Data Structures
9
}
Summer 2015: June 9
© R. Mak
Feed Our Pets, cont’d

Instead of:
HouseholdPet pet = (HouseholdPet) animals[i];
pet.feed(f);
you can write:
((HouseholdPet) animals[i]).feed(f);
The first way may be easier to write and read!
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
10
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.
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
11
Avoid Biters!

Example of how to use a marker interface:
Animal animals[];
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.
}
}
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
12
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
...
}
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
13
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(...);
Interface
type
Computer Science Dept.
Summer 2015: June 9
Implements the
HouseholdPet
interface
CS 46B: Introduction to Data Structures
© R. Mak
14
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(...);
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
15
Break
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
16
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.
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
17
Create a Scanner Object

The constructor for the Scanner class
can have a reference to a File object
as its argument:
File inputFile = new File("myinput.txt");
Scanner in = new Scanner(inputFile);

Or:
Scanner in = new Scanner(new File("myinput.txt"));

The Scanner class lives in the java.util
package, so you must import it:
import java.util.Scanner;
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
18
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:
PrintWriter out = new PrintWriter("myoutput.txt");

The PrintWriter class lives in the java.io
package, so you must import it:
import java.io.PrintWriter;
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
19
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.
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
20
Close the Input and Output Files

When your program is done with an input
or an output file, it should close it:
in.close();
out.close();

// close the Scanner input file
// close the PrintWriter output file
If you don’t close an output file, the last part
of your output may not make it into the file.
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
21
Clicker Question June 9 #2

Consider the statement
Scanner in = new Scanner("myinput.txt");
a.
b.
c.
d.
This is a runtime error because the Scanner
constructor expects a reference to a file object.
This is a compile-time error because the Scanner
constructor expects a reference to a file object.
This is acceptable because your program will read
from an input file named myinput.txt.
This is acceptable because your program will read
from the string "myinput.txt".
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
22
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.
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
23
Read Words, cont’d

How do you read one word after another
from an input text file?

Suppose variable in is a reference
to a Scanner object:
while (in.hasNext()) {
String word = in.next();
System.out.println(word);
}

How does this loop work?
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
24
Read Words, cont’d
while (in.hasNext()) {
String word = in.next();
System.out.println(word);
}

If the input file contains
Mary had a little lamb

What is the output?
Mary
had
a
little
lamb
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
25
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
Mary had 12 little #%@&!! lambs.
the output will be
Computer Science Dept.
Summer 2015: June 9
Mary
had
12
little
#%@&!!
lambs.
Why?
CS 46B: Introduction to Data Structures
© R. Mak
26
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”.
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
27
Read Characters

If you want to read a text file one character
at a time, set the delimiter to an empty string:
in.useDelimiter("");

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?
while (in.hasNext()) {
char ch = in.next().charAt(0);
/* do something with ch */
}
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
28
Classify Characters

Each of the following boolean methods
takes a character as an argument.
Typo: It should be
isWhitespace
(lower-case s).
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
29
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.
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
30
Read Lines, cont’d

How do you read one line after another
from an input text file?

Suppose variable in is a reference
to a Scanner object:
while (in.hasNextLine()) {
String line = in.nextLine();
System.out.println(line);
}

How does this loop work?
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
31
Read Numbers

The Scanner class has methods to read
numbers, including:



hasNextInt() and nextInt()
hasNextLong() and nextLong()
hasNextDouble() and nextDouble()
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
32
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.
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
33
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?
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
34
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. */
}
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
35
Introduction to Exception Handling, cont’d
try {
...
}
The exception variable ex
catch (SomeException ex) { contains useful information about
the exception that just occurred.
...
}

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.
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
36
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;
Computer Science Dept.
Summer 2015: June 9
}
CS 46B: Introduction to Data Structures
© R. Mak
37
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();
}
Why do we need to check
finally {
if (in != null) in.close(); whether in is null?
}
No matter whether the try block executed normally,
or an exception occurred
and the catch block executed,
Computer Science Dept.
CS 46B: Introduction to Data Structures
Summer
2015:always
June 9
© R. Mak
we will
close the input file.
38
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
Computer Science Dept.
Summer 2015: June 9


white-space characters
other characters
CS 46B: Introduction to Data Structures
© R. Mak
39
Homework #2, cont’d

Draft: Due Wednesday, June 10 at 11:59 PM



Just count and print the number of
lines, words, and characters.
Canvas:
URL:
Homework 2 Draft
http://codecheck.it/codecheck/files/1506091032cjhe
4tuyws7nwgo420hi8tkw8
Final: Due Friday, June 12 at 11:59 PM


Also calculate and print the percentages.
Canvas:
URL:
Homework 2 Final
http://codecheck.it/codecheck/files/1506091036ay0z
b7ctd13x92r8zy4xs7h7y
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
40
Homework #2, cont’d

Input file GettysburgAddress.txt:
http://www.cs.sjsu.edu/~mak/CS46B/assignmen
ts/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.
Computer Science Dept.
Summer 2015: June 9
CS 46B: Introduction to Data Structures
© R. Mak
41