Download presentation
Presentation is loading. Please wait.
Published byEdward Sutton Modified over 9 years ago
1
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
2
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak Quiz 6 June 11 Take “Quiz 6 June 11” in Canvas before the start of Thursday’s class. 2
3
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 3 A Class Hierarchy Puzzle Animal LionDogPiranhaGoldfishParrotHummingbird MammalFishBird 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”
4
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 MammalFishBird LionDogPiranhaGoldfishParrotHummingbird «interface» HouseholdPet «interface» Biter
5
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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. 5 public interface HouseholdPet { void feed(Food f); }
6
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 MammalFishBird LionDogPiranhaGoldfishParrotHummingbird
7
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 MammalFishBird LionDogPiranhaGoldfishParrotHummingbird «interface» HouseholdPet «interface» Biter
8
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
9
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); } }
10
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!
11
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.
12
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[];
13
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... }
14
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 the HouseholdPet interface Interface type
15
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(...);
16
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak Break 16
17
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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. 17
18
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak Create a Scanner Object The constructor for the Scanner class can 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: 18 File inputFile = new File("myinput.txt"); Scanner in = new Scanner(inputFile); Scanner in = new Scanner(new File("myinput.txt")); import java.util.Scanner;
19
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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: 19 PrintWriter out = new PrintWriter("myoutput.txt"); import java.io.PrintWriter;
20
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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. 20
21
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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. 21 in.close(); // close the Scanner input file out.close(); // close the PrintWriter output file
22
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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". 22 Scanner in = new Scanner("myinput.txt");
23
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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. 23
24
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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: How does this loop work? 24 while (in.hasNext()) { String word = in.next(); System.out.println(word); }
25
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak Read Words, cont’d If the input file contains What is the output? 25 while (in.hasNext()) { String word = in.next(); System.out.println(word); } Mary had a little lamb Mary had a little lamb
26
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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 be 26 Mary had 12 little #%@&!! lambs. Mary had 12 little #%@&!! lambs. Why?
27
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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 27 in.useDelimiter("[^A-Za-z]+"); A “regular expression” that says “one or more characters that is not a letter”.
28
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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? 28 in.useDelimiter(""); while (in.hasNext()) { char ch = in.next().charAt(0); /* do something with ch */ }
29
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak Classify Characters Each of the following boolean methods takes a character as an argument. 29 Typo: It should be isWhitespace (lower-case s).
30
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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. 30
31
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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: How does this loop work? 31 while (in.hasNextLine()) { String line = in.nextLine(); System.out.println(line); }
32
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak Read Numbers The Scanner class has methods to read numbers, including: hasNextInt() and nextInt() hasNextLong() and nextLong() hasNextDouble() and nextDouble() 32
33
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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. 33
34
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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? 34
35
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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. 35 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. */ }
36
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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. 36 try {... } catch (SomeException ex) {... } The exception variable ex contains useful information about the exception that just occurred.
37
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak FileNotFoundException Handler Example 37 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; }
38
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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. 38 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 check whether in is null?
39
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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 39 white-space characters other characters
40
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak 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/1506091032cjhe 4tuyws7nwgo420hi8tkw8 http://codecheck.it/codecheck/files/1506091032cjhe 4tuyws7nwgo420hi8tkw8 Final: Due Friday, June 12 at 11:59 PM Also calculate and print the percentages. URL: http://codecheck.it/codecheck/files/1506091036ay0z b7ctd13x92r8zy4xs7h7y http://codecheck.it/codecheck/files/1506091036ay0z b7ctd13x92r8zy4xs7h7y 40 Canvas: Homework 2 Draft Canvas: Homework 2 Final
41
Computer Science Dept. Summer 2015: June 9 CS 46B: Introduction to Data Structures © R. Mak Homework #2, cont’d Input file GettysburgAddress.txt : http://www.cs.sjsu.edu/~mak/CS46B/assignmen ts/2/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. 41
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.