Review of OOP in Java What you should already know…. (Appendices C, D, and E)

Slides:



Advertisements
Similar presentations
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Advertisements

Written by: Dr. JJ Shepherd
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
UML Basics & Access Modifier
Week 14 - Monday.  What did we talk about last time?  Image manipulation  Inheritance.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Chapter 8. About the Midterm Exam.. Exam on March 12 Monday (Tentatively) Review on March 7 Wednesday Cover from Chapter 6 Grades will be out before spring.
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
10-Nov-15 Java Object Oriented Programming What is it?
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226.
Week 14 - Monday.  What did we talk about last time?  Inheritance.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
Week101 APCS-AB: Java Miscellaneous Topics: Snippets we missed in Chapters 1-6 of book November 11, 2005.
Exam tip! str.equals(), str.startsWith(), str.toUpperCase() kbd.next(), kbd.nextLine(), etc Exam tip! str.equals(), str.startsWith(), str.toUpperCase()
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming –TextField Action Listeners, JEditorPane action listeners, HTML in a JEditorPane,
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Lecture 7 February 24, Javadoc version and author Tags These go in the comments before named classes. –Put your SS# on a separate line from the.
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
Creating a GUI Class An example of class design using inheritance and interfaces.
CS2102: Lecture on Abstract Classes and Inheritance Kathi Fisler.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CS1101 Group1 Discussion 6 Lek Hsiang Hui comp.nus.edu.sg
Written by: Dr. JJ Shepherd
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
1 Introduction to Object Oriented Programming Chapter 10.
Methods II Material from Chapters 5 & 6. Note on the Slides  We have started to learn how to write non- program Java files  classes with functions/methods,
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Introduction to Exceptions in Java CS201, SW Development Methods.
Data, Classes, and Objects Classes with Data Classes for Data (Chapter 5)
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
GUIs and Events Rick Mercer.
Exceptions Chapter 9.
“Form Ever Follows Function” Louis Henri Sullivan
Inheritance and Polymorphism
Data, Classes, and Objects
Week 14 - Wednesday CS 121.
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
What you should already know…. (Appendices C, D, and E)
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
CMPE212 – Reminders Quiz 1 marking done. Assignment 2 due next Friday.
Exceptions 10-May-19.
CMPE212 – Reminders Assignment 2 due next Friday.
Throwing, Catching Defining
Presentation transcript:

Review of OOP in Java What you should already know…. (Appendices C, D, and E)

Outline  Encapsulation  Inheritance & Polymorphism  GUI as an example of I & P  Exceptions

Encapsulation  Classes and objects:  reference and co-reference  data and operations  Methods and constructors  arguments and parameters  overloading  javadoc comments  Static fields and methods

Classes and Objects  Class encapsulates data and operations  keeps them together in one place String name = “Mark Young”;// data int len = name.length();// 10 int space = name.indexOf(“ ”);// 4 (sic) String city = “Wolfville”;// more data String animal = city.substring(0,4);// “Wolf”  Class: String  objects: “Mark Young”, “Wolfville”, “Wolf” »object variables: name, city, animal

Classes, Objects and Variables  Class is a kind of thing; a data type  the kind of data and the available operations  Object is an instance of the class; something a variable can refer to  variables refer to, or point to, objects & name: “Mark Young” & city: “Wolfville” & animal: “Wolf” String variablesString objectsString operations get length find index of get substring …

Reference and Co-Reference  Two variables can refer to the same object Car myCar = new Car(blue);// data Car disCar = myCar;// same object Car steves = new Car(blue);// same data disCar.setColor(green);// myCar is now green & myCar: & disCar: & stevesCar: Car variablesCar objectsCar operations … get colour change colour …

Data  What we know about objects of this class  class says what type it is  object holds information Class Name: Car Data: make:(String) model:(String) year:(int) fuel (l):(double) mileage (km): (double) colour:(Color) Operations: … make:Toyota model:Corolla year:2009 fuel (l):23.7 mileage (km): colour:RED myCar

Data Declaration  Data saved in instance variables  variables declared in the class  access level (usually private, unless final)  if final (never going to change)  data type (int, double, String, Color, …)  name public final String MAKE, MODEL; public final int YEAR; private double fuel, mileage; private Color colour;

Why Private? Why Public?  IVs are made private to keep clients from messing them up  accidentally or maliciously  not allowed to say myCar.mileage = ; »error: mileage is PRIVATE!  Final variables can’t get messed up  given value when object created; never changes  not allowed to say myCar.YEAR = 2013; »error: YEAR is FINAL!

Operations  What we can do with objects of this class  class says what’s available  object carries out actions Class Name: Car Data: … Operations: get mileage drive some distance add fuel get colour change colour … make:Toyota model:Corolla year:2009 fuel (l):23.7 mileage (km): colour:RED myCar make:Toyota model:Corolla year:2009 fuel (l):17.4 mileage (km): colour:RED myCar myCar, drive 96.3 km.

Methods  In OOP, operations become methods  length operation  length method  change colour operation  setColor method  Methods addressed to objects  usually thru a variable…  name.length(), myCar.drive(96.3), …  …but not necessarily!  “Hello”.length(), Math.pow(10, 3), …  “calling the method”

Method Header/Interface  First line of method definition  access level (operations public, helpers private)  if static (shared by whole class)  void or return type (int, double, String[], …)  method name  parameter list public void setColor (Color c) public Color getColor () public static double pow (double base, double exponent)

Parameters/Arguments  Parameters are variables  data type and name  (double base, double exponent), (int n), (Color c), …  Arguments are values  of the correct type »int num = 10;  (10.5, 3.14), (num), (new Color(0, 255, 0)), …  Method call sets parameters to arguments  base = 10.5; exponent = 3.14

Getters and Setters  Methods to get some part of object’s data  getter: getMileage, getFuel, getColor, … »most (non-final) IVs will have getters  Methods to change some part of data  setter: setColor »no setters for final instance variables »no setters for fuel and mileage but addFuel and drive will change them (“mutaters”)but addFuel and drive will change them (“mutaters”)  “immutable” objects have no setters at all!

Referring to IVs  Method definitions can refer to instance variables by name in any method mileage += distance; return colour;  but to emphasize that it’s this object’s data: this.mileage += distance; return this.colour; »useful when a parameter has the same name: public void setColor(Color colour) { this.colour = colour;// IV colour set to parameter colour this.colour = colour;// IV colour set to parameter colour}

Private Methods  Methods can be declared private  client can’t use these methods »so not for the class operations  they can only be called from inside this class »only to “help” this class carry out its operations  public methods should check their parameters »to make sure they make sense  private methods can assume they’re OK »if they’re not, then we need to fix our code

Overloading  Methods in same class can share names  called “overloading” the method (name)  must have different parameter lists »different number of parameters »or different types of parameters  related/similar operations public double addFuel(double x) { … } … »add given number of litres of fuel public double addFuel() { … } »fill the tank

Constructors  Put the initial information into the object  use “new” command  give required data  assign to a variable (usu.) Car myCar = new Car( “Toyota”, “Corolla”, 2009, Color.RED); »fuel and mileage start at 0.0 / myCar make:/ model:/ year:0 fuel (l):0.0 mileage (km):0.0 colour:/ myCar make:Toyota model:Corolla year:2009 fuel (l):0.0 mileage (km):0.0 colour:RED myCar

Constructor Definition  Different from method definitions  access usually public (but can be private, …)  never static  no void/return type at all  name is same as name of class public class Car { public Car(String make, String model, int year, Color c) { …}

Constructor Purpose  Make sure every instance variable gets a reasonable value  what the client asks for it to be, if possible  some reasonable default if client doesn’t say »may depend on what else client asks for  Constructor is only place where a final variable can be given a value

Overloaded Constructors  Like overloaded methods, must have different parameter lists public Car(String make, String model, int year, Color c) public Car(int year, String make, String model, Color c) public Car(String make, String model, int year) public Car(int year, String make, String model) public Car(Color c)

Primary Constructor  Generally pick one constructor as primary  it makes sure every IV gets a good value  Other constructors call the primary: this(…)  add in arguments for missing parameters  may do extra work afterwards public Car(int year, String make, String model, Color c) { this(make, model, year, c); } public Car(Color c) { this(“Generic”, “Auto”, 1997, new Color(127, 63, 70)); // “rust” }

javadoc Comments  Comments on classes and methods  used to build Web documentation  between /** and */  description of class/method  tags …  tags …

javadoc Example /** * A simple class. * A simple class. Mark Young (A ) Mark Young (A )*/ public class Simple { /** /** * A useless method. * A useless method. nthe count of something nthe count of something xthe length of something else xthe length of something else totally unrelated value totally unrelated value */ */ public String useless(int n, double x) { public String useless(int n, double x) { return “What?”; return “What?”; }}

Course Requirements  Class javadoc includes brief description (with name and A-number)  Method/constructor javadoc requires brief description and for every parameter for value-returning methods for checked exceptions thrown

Pre- and Post-Conditions  Precondition: something that must be true in order for the method to work  client’s responsibility to make sure it’s true »if it’s not true, then it’s the client’s fault the method doesn’t work  Postcondition: things that will be true after method is done  assumes preconditions are true »otherwise “all bets are off”

Static Fields and Methods  “Static” = shared by all members of class  common constants public static final double PI = ;  object count private static int numberOfCarsCreated = 0; public static int getNumberOfCarsCreated()  special object creation methods public static Point cartesian(double x, double y) public static Point polar(double r, double theta)  …

Inheritance and Polymorphism  Composition vs. Inheritance  Inheritance  adding fields and methods  overriding  polymorphism  constructors  Interfaces

Composition vs. Inheritance  Composition: “has a” »has that kind of an instance variable  Person has a Name  Car has a Color  Inheritance: “is a” »is that (more general) kind of a thing  Student is a Person  Car is a Vehicle

Inheritance  Get all the public methods of another class  the data, too, but it’s sort of hidden from you  Use “extends” in class declaration public class Student extends Person »a Student can do anything a Person can do »a Student has all the data a Person has public class Car extends Vehicle »a Car can do anything a Vehicle can »a Car has all the data a Vehicle has

Inherited Methods and Data  “Subclass” has all methods of “superclass”  Person has thinkAbout method…  …so Student has thinkAbout method »doesn’t need to even say it has the method  includes getters and setters »Person has getName method… »…so Student has getName method  Private data still private to the superclass  Student must use getName/setName

Adding Fields and Methods  “Sub-class” can add new IVs and methods  just declare them like usual private double grade; public double getGrade() { return grade; }  belong only to objects in the subclass »Student has getGrade method double studentsGrade = stu.getGrade(); »Person doesn’t! double personsGrade = guy.getGrade(); error: can’t find symbol method getGradeerror: can’t find symbol method getGrade

Overriding Methods  Subclass can add a method with same name as one in the superclass  if different parameter list, then it’s an overload  if same parameter list, then it’s an override »it replaces (hides/shadows) inherited method »subclass does same method in a different way  before method definition

Object Class and Methods  Every class inherits from Object  directly or indirectly »if you don’t say you extend, then you extend Object »if you do say, then it extends Object (dir. or indir.)  Some Object methods we often override: public String toString() »make a String that represents this object public boolean equals(Object that) »check whether this object has same data as that

Polymorphism  Subclass is a superclass  so when we need a superclass object…  …a subclass object will do »Need a Person? Use a Student! public static void greet(Person p) { … } Person guy = new Person(); Student stu = new Student(); greet(guy);// guy is a Person greet(stu);// stu is a Person (all Students are)

Constructors  Subclass object must be constructed  but subclass object is a superclass object…  …so superclass object must be constructed, too »Java needs to be told how to do that  use super(…) to call superclass constructor »give whatever information is relevant public Student(String name, double grade) { super(name);// calls Person(String name) super(name);// calls Person(String name) this.grade = grade; this.grade = grade;}

Primary Constructors  Can’t use both this(…) and super(…)  both of them need to be first »so you can only use one or the other  Call super(…) from the primary constructor  for secondary constructors, use this(…) »call primary constructor, which then calls super(…)

Interfaces  Basically a list of method headers  operations something might be able to do  Represent a “skill set”  says “what” but not “how”  Sample interfaces  List : can keep track of a list of T objects »T is any reference type (class or interface)  Comparable : can be compared to T objects  Comparator : can compare T objects

Sample Interface  Measurable: has an area and a perimeter public interface Measurable { /** get the area of this object /** get the area of this object the area of this object */ the area of this object */ public double getArea(); public double getArea(); /** get the perimeter of this object /** get the perimeter of this object the perimeter of this object*/ the perimeter of this object*/ public double getPerimeter(); public double getPerimeter();}

Having the Skill Set  Any class that has getArea and getPerimeter has the skills necessary to be a Measurable  but it must tell Java it has the skill set public class Circle implements Measurable { private double radius; private double radius; public Circle(double r) { … } public Circle(double r) { … } public getRadius() { … } public getRadius() { … } public double getArea() { … } public double getArea() { … } public double getPerimeter() { … } public double getPerimeter() { … }} public class Rectangle implements Measurable { private double length, width; private double length, width; …

Polymorphism  Interfaces can be used as data types public static double roundness(Measurable m) { return 4 * Math.PI * m.getArea() / Math.pow(m.getPerimeter(), 2); return 4 * Math.PI * m.getArea() / Math.pow(m.getPerimeter(), 2);}  any class that implements the interface will do »but it has to say that it implements the interface…. double rc = roundness(new Circle(10.0)); double rr1 = roundness(new Rectangle(10.0, 20.0)); double rr2 = roundness(new Rectangle(0.4, )); 1.0 rc rr rr2

GUI as an Example of I&P  The JFrame class  components and layout  inheriting from JFrame  The ActionListener interface  adding an action listener  (anonymous action listeners?)

The JFrame Class  javax.swing.JFrame is a window class  constructor takes window title  need to set its size & make it visible »otherwise it’s tiny and invisible JFrame win = new JFrame(“An Empty Window”); win.setSize(300, 200); win.setVisible(true);

Window Components  Want to add stuff to the window win.add(new JLabel(“Hello!”), BorderLayout.NORTH); win.add(new JTextField(), BorderLayout.CENTER); win.add(new JButton(“OK”), BorderLayout.SOUTH); »there are other ways to lay out the window

New Window Classes  Create a class that extends JFrame  class is another window class public class AdderDialog extends JFrame { … }  Use constructor to add labels, buttons, etc. »we’re using a GridLayout (5 x 2) here »and Unix… AdderDialog d; d = new AdderDialog(); d.setVisible(true);

Instance Variables  Window needs to track its pieces  except for the labels – they do nothing private JTextBox firstNumberBox; private JTextBox secondNumberBox; private JTextBox resultBox; private JButton calculateButton; private JButton doneButton;

Window Constructor Tasks  Constructor:  calls parent constructor: super(“Adding Numbers”);  sets the size  sets layout: this.setLayout(new GridLayout(5, 2));  creates and adds the required elements firstNumberBox = makeNumberBox();// private method … this.add(new JLabel(“First number:”)); this.add(firstNumberBox);…

Getting Some Action  Our buttons do nothing »well, they change colour a bit when they’re clicked  want them to do something  need an object that knows how to react to them »that object needs to listen for the button’s click »that object needs access to the number boxes  the ActionListener interface »the actionPerformed(ActionEvent e) method »the ActionEvent’s getSource() method

The ActionListener Interface  Knows how to respond to an event  create an ActionListener object (“AL”) public class AL implements ActionListener { public void actionPerformed(ActionEvent e) { … } public void actionPerformed(ActionEvent e) { … }}  tell button AL is listening to it doneButton.addActionListener(new AL());  click  AL’s actionPerformed method is called »but AL will need access to AdderDialog’s IVs »maybe AdderDialog should be the ActionListener

Listening to Own Components  Have window implement ActionListener public class AdderDialog extends JFrame implements ActionListener { … } »important: extends first, implements after  tell buttons that this window is listening to them doneButton.addActionListener(this); calculateButton.addActionListener(this);  must now implement actionPerformed

The actionPerformed Method  Argument has information about the event  including its “source”: which button it was »choose action based on button clicked public void actionPerformed(ActionEvent e) { Object clicked = e.getSource(); Object clicked = e.getSource(); if (clicked == doneButton) { if (clicked == doneButton) { System.exit(0);// end program System.exit(0);// end program } else if (clicked == calculateButton) { } else if (clicked == calculateButton) { addTheNumbers();// private method addTheNumbers();// private method }}

Adding the Numbers  Private method to add and report result  use getText and Integer.parseInt to read #s  use setText and Integer.toString to show result private void addTheNumbers() { int n1 = Integer.parseInt(firstNumberBox.getText()); int n1 = Integer.parseInt(firstNumberBox.getText()); int n2 = Integer.parseInt(secondNumberBox.getText()); int n2 = Integer.parseInt(secondNumberBox.getText()); resultBox.setText(Integer.toString(n1 + n2)); resultBox.setText(Integer.toString(n1 + n2));}

Exceptions  Exceptions  File Open Exceptions  Input Exceptions  The Exception Class  The throws Clause

Adding the Numbers  Private method to add and report result  use getText and Integer.parseInt to read #s  use setText and Integer.toString to show result private void addTheNumbers(); int n1 = Integer.parseInt(firstNumberBox.getText()); int n1 = Integer.parseInt(firstNumberBox.getText()); int n2 = Integer.parseInt(secondNumberBox.getText()); int n2 = Integer.parseInt(secondNumberBox.getText()); resultBox.setText(Integer.toString(n1 + n2)); resultBox.setText(Integer.toString(n1 + n2));}

Exceptions  Objects that represent problems in program  problems that the program itself might be able to do something about  Throw and Catch  method with problem throws the exception  method that can deal with it will catch it  method must be ready to catch it: »the try-catch control

The NumberFormatException  Exception in the AdderDialog program  what if user enters text into number box? »Integer.parseInt can’t change it to a number »throws a NumberFormatException »AdderDialog does nothing about it addition FAILSaddition FAILS  can AdderDialog do anything about it? »could set result box to “ERROR” lets user know something’s wrong, at least!lets user know something’s wrong, at least!

Dealing with the Exception  Try to add the numbers; catch the exception private void addTheNumbers() { try { try { int n1 = Integer.parseInt(firstNumberBox.getText()); int n1 = Integer.parseInt(firstNumberBox.getText()); int n2 = Integer.parseInt(secondNumberBox.getText()); int n2 = Integer.parseInt(secondNumberBox.getText()); resultBox.setText(Integer.toString(n1 + n2)); resultBox.setText(Integer.toString(n1 + n2)); } catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) { resultBox.setText(“ERROR”); resultBox.setText(“ERROR”); }} »no exception: numbers get added up »exception: result gets set to “ERROR”

Try-Catch Control  Try block contains the code we want to do  but might throw an exception we can deal with  Catch block has code to deal with problem  says what kind of problem it deals with »e.g. NumberFormatException  If try block works, catch block gets skipped  If exception happens, jump to catch block  remainder of try block gets skipped

File I/O  Exceptions also important for file i/o  problem trying to connect to the file  The FileNotFoundException  trying to read from a file that doesn’t exist  trying to read from a read-protected file  trying to create a file in a write-protected folder  Need to deal with it  it’s a “checked” exception

Quitting  Try to open a file with necessary data Scanner in = null; try { in = new Scanner(new File(“Important.dat”)); in = new Scanner(new File(“Important.dat”)); } catch (FileNotFoundException fnf) { System.err.println(“Could not read important data.”); System.err.println(“Could not read important data.”); System.err.println(“Quitting.”); System.err.println(“Quitting.”); System.exit(1); System.exit(1);} int importantNumber = in.nextInt(); …

Trying Again  User chooses file to process Scanner in = null; do { try { try { System.out.print(“Enter file name: ”); System.out.print(“Enter file name: ”); String name = kbd.nextLine(); String name = kbd.nextLine(); in = new Scanner(new File(name)); in = new Scanner(new File(name)); } catch (FileNotFoundException fnf) { } catch (FileNotFoundException fnf) { System.out.println(“Could not open that file.”); System.out.println(“Could not open that file.”); } } while (in == null);

Using System.out  Trying to create a file, but fail! PrintWriter out = null; try { System.out.print(“Enter file name: ”); System.out.print(“Enter file name: ”); String name = kbd.nextLine(); String name = kbd.nextLine(); out = new PrintWriter(new File(name)); out = new PrintWriter(new File(name)); } catch (FileNotFoundException fnf) { System.out.println(“Could not open that file.”); System.out.println(“Could not open that file.”); System.out.println(“Using System.out….”); System.out.println(“Using System.out….”); out = new PrintWriter(System.out); out = new PrintWriter(System.out);}

Input Exceptions  Exceptions may happen in reading as well  user enters word where number expected »InputMismatchException  file runs out of data early »NoSuchElementException  Can deal with these as well  but don’t need to

Input Exceptions  Read numbers from file »may be words in file; may be too few numbers for (int i = 0; i < N; ++i) { try { try { arr[i] = in.nextInt(); arr[i] = in.nextInt(); } catch (InputMismatchException ime) { } catch (InputMismatchException ime) { arr[i] = -1;// indicates bad input arr[i] = -1;// indicates bad input in.next();// skip bad input in.next();// skip bad input } catch (NoSuchElementException nse) { } catch (NoSuchElementException nse) { break;// no sense trying to read any more! break;// no sense trying to read any more! }}

Multiple Catch Blocks  Can have as many catch blocks as you like  each for a different kind of exception  Catch order may be important  some exception classes inherit from others »InputMismatchExc n is a NoSuchElementExc n »if you ask for an int, and the next thing is a word, then there’s no such thing as what you asked for  must put more specific exceptions first »IME must come before NSEE

Never Catch Exception  Exception is most general exception class  if have catch(Exception e), it must come last  But DON’T CATCH IT!  it captures every kind of exception »including many you shouldn’t deal with  what could you possibly do that would deal with every possible kind of problem?

The throws Clause  If your code may throw a checked exception and your method doesn’t deal with it, then you need to tell Java you won’t deal with it »that’s what being “checked” means  add throws clause to method header private static Scanner open(String name) throws FileNotFoundException { return new Scanner(new File(name)); return new Scanner(new File(name));}

Questions