Big Java - PowerPoint PPT Presentation

1 / 30
About This Presentation
Title:

Big Java

Description:

More File I/O Options. Can hardcode a filename: in = new fileReader('c:hwkin.dat' ... Is a tire a circle? No, tire is a car part; circle is a geometric object. ... – PowerPoint PPT presentation

Number of Views:48
Avg rating:3.0/5.0
Slides: 31
Provided by: cyndi8
Category:
Tags: big | java | tires

less

Transcript and Presenter's Notes

Title: Big Java


1
Big Java
  • Chapters 11-12

2
  • Chapter 11
  • Input/Output and
  • Exception Handling

3
Reading Writing Text Files
  • import java.io. // FileReader, exception and
    PrintWriter
  • import java.util.Scanner
  • public class LineNumberer
  • public static void main(String args) throws
    FileNotFoundException
  • Scanner console new Scanner(System.in)
  • System.out.print("Input file ")
  • String inputFileName console.next()
  • System.out.print("Output file ")
  • String outputFileName console.next()
  • FileReader reader new FileReader(inputFile
    Name)
  • Scanner in new Scanner(reader)
  • PrintWriter out new PrintWriter(outputFile
    Name) // overwrites
  • int lineNumber 1
  • while (in.hasNextLine() )
  • String line in.nextLine()

4
More File I/O Options
  • Can hardcode a filename
  • in new fileReader(c\\hwk\\in.dat)
  • Can display a file dialog (more convenient GUI
    for casual user)
  • JFileChooser chooser new JFileChooser()
  • FileReader reader null
  • if (chooser.showOpenDialog(null)
  • JFileChooser.APPROVE_OPTION)
  • File selectedFile chooser.getSelectedFile()
  • reader new FileReader(selectedFile)
  • Can be a command line argument (easier to
    automate)
  • if (args.length gt 1)
  • inputFileName args0

5
Eclipse New Run Configuration
  • Select Run icon
  • Press New Configuration Icon (be sure Java
    application is selected)

Fill in Name, Project and Main Class as needed
6
Eclipse Arguments
  • Click on Arguments tag to add Program Arguments

7
What to do about errors?
  • Exceptions handled in try/catch block
  • try
  • String filename . . .
  • FileReader reader new FileReader(filename)
  • Scanner in new Scanner(reader)
  • String input in.next()
  • int value Integer.parseInt(input)
  • catch (FileNotFoundException exception)
  • System.out.println(File not found)
  • catch (IOException e) // would also catch
    FileNotFound
  • e.printStackTrace() // catches
    NoSuchElementException
  • catch (NumberFormatException e)
  • System.out.println(Input was not a number)

8
Quality Tip
  • Throw Early, Catch Late. Better to throw an
    exception than come up with an imperfect fix.
    What should program do if a file is not found?
    Is it always an error?
  • Do not squelch exceptions.
  • try
  • FileReader reader new FileReader(filename)
  • catch (Exception e) // So there!

9
Checked and Unchecked
  • Checked exceptions cant ignore, compiler
    requires that you handle or propagate
  • Unchecked exceptions can be ignored. Generally
    subclass of RuntimeException, like
    NumberFormatException or NullPointerException.
    Too expensive to check all of these, often due to
    programmer error (checked exceptions often user
    error, like InputMismatchException)
  • If you arent going to handle a checked
    exception, put throws clause on function header
  • public void read(String filename) throws
    FileNotFoundException
  • . . .

10
Exception Hierarchy
Throwable
Exception
Error
IOException
RuntimeException
ClassNot FoundException
CloneNot Supported Exception
ArithmeticException
ClassCastException
EOFException
IllegalStateException
FileNotFoundException
NumberFormatException
MalformedURLException
IndexOutOfBoundsException
UnknownHostException
ArrayIndexOutOfBoundsException
NoSuchElementException
NullPointerException
11
Finally Clause
  • Sometimes cleanup is needed even after an
    exception occurs
  • PrintWriter out new PrintWriter(filename)
  • try
  • writeData(out)
  • finally
  • out.close() // always executed, including after
  • // exception is handled in a catch
  • Quality tip dont mix catch and finally in the
    same try statement, see tip 11.3

12
Designing your own Exception
  • public class InsufficientFundsException
  • extends RuntimeException
  • public InsufficientFundsException()
  • public InsufficientFundsException (String
    message)
  • super(message)

Customary to have two constructors
Must decide which to extend external event or
programmer? If programmer should prevent, make
unchecked (Runtime)
13
Example of Exception Handling
main handles all exceptions
14
Example (continued)
Exceptions passed back to main to handle
Ensures resources are cleaned up
User-defined exception
15
Example (continued)
BadDataException thrown with appropriate
errors for specific problems with input file (no
initial length, too many value, not enough
values)
16
Reading Assignment
  • Read Random Fact 11.1 The Ariane Rocket
    Incident, page 520

17
  • On to Chapter 12
  • Object-Oriented Design

18
Software Process - Waterfall
What do customers really want?
Does not work well when rigidly applied!
Analysis
Design
Design not very efficient, but oh well
Inconsistent requirements?
Implementation
Testing
Deployment
established early 1970s
Customers not happy ?
19
Software Process Spiral
Issue s/w engineers may think there will always
be another iteration, dont deliver quality
Design
Implementation
Analysis
prototype 1
prototype 2
Testing
final product
Deployment
implement prototypes quickly
should be spirals, not circles, but no arcs in PP
20
Reading Assignment
  • Random Fact 12.1, Programmer Productivity, page
    535

21
Discovering Classes
  • Required tasks
  • Discover classes
  • Determine responsibilities of each class
  • Describe relationships between classes
  • Weve already talked about using nouns as
    possible classes/objects and verbs as the
    possible methods.

22
Points to Consider
  • A class represents a set of objects with the same
    behavior. The design should capture the
    commonalities.
  • Some entities will be objects, others will be
    primitive types. How to decide? Example an
    address could either be a simple string or a
    class. If your system needs to do special
    processing on the address, a class may be called
    for. Otherwise, keep it simple.
  • Not all classes will be discovered in analysis
    phase. Most systems have extra classes for
    tactical purposes, such as database access, GUI,
    etc.
  • Use existing classes, extended as needed, where
    you can.

23
Assigning methods - CRC
  • Sometimes it is difficult to determine which
    class should implement a particular method.
  • CRC card method Classes, Responsibilities,
    Collaborators
  • Use index card for each class
  • Write responsibilities on the class card
  • Also record which other classes are needed to
    fulfill that task (collaborators)

24
CRC Example
Responsibilities
Collaborators
Invoice
compute amount due
LineItem
Does this class have needed methods? such as
getTotalPrice?
These should be high level
Tasks can be simulated by moving tokens from one
card to the next as objects are called on to do
their methods
25
Class Relationships
  • Be sure inheritance really represents is-a
    relationships. Is a tire a circle? No, tire is
    a car part circle is a geometric object. A tire
    has a circle as its boundary.
  • public class Tire
  • private Circle boundary
  • This type of relationship is called aggregation.

26
Another example
  • public class Car extends Vehicle
  • private Tire tires

is-a (inheritance)
Vehicle
has-a (aggregation)
Car
UML Symbols
Inheritance Interface Implementation Aggregation D
ependency
Tire
27
More UML
  • UML class diagrams may list attributes (often
    instance variables) and methods. Actual class may
    not store data that way (e.g., Date class stores
    as milliseconds, but has day, month and year
    attributes)
  • May not list all attributes and methods, depends
    on purpose of diagram
  • Dont list as attribute if also an aggregation
  • May show multiplicities for aggregates
  • any number
  • one or more 1..
  • zero or one 0..1
  • exactly one 1

28
Association
  • Sometimes has doesnt really represent
    relationship
  • Does bank have customers, do customers have
    bank?
  • More general relationship is association
  • Use solid line with arrows to show that its
    possible to navigate from objects of one class to
    objects of another
  • May add text to explain relationship (e.g.,
    serves on line from Bank to Customer)
  • Association vs Aggregation not an important
    distinction use it if it helps make design
    clearer!

29
More UML Examples
1..
Customer
BankAccount
serves
Customer
Bank
Bank Account balance deposit() withdraw()
30
CRC Exercise
  • Apply the CRC method to develop classes for the
    stories you wrote in the previous exercise
  • Create UML diagrams for those classes
Write a Comment
User Comments (0)
About PowerShow.com