Final Exam Review - PowerPoint PPT Presentation

1 / 39
About This Presentation
Title:

Final Exam Review

Description:

The files created can be read by other Java programs but are not printable ... Text files contain strings of printable characters; they look intelligible to ... – PowerPoint PPT presentation

Number of Views:53
Avg rating:3.0/5.0
Slides: 40
Provided by: lew125
Category:
Tags: exam | final | printable | review

less

Transcript and Presenter's Notes

Title: Final Exam Review


1
Final Exam Review
  • Exam is
  • Wednesday, December 10, 900 a.m.

2
Most Important
  • Understand all lab assignments
  • Understand all homework assignments

3
Emphasis Since Last Test
  • Event-Driven Programming (GUIs with active
    components)
  • Input/Output
  • Exceptions
  • Threads
  • HTML, Javascript, and Web Pages
  • Javadoc and Java Style

4
Streams and File I/O
  • Overview of Streams and File I/O
  • Text File I/O
  • Binary File I/O
  • File Objects and File Names

5
Streams
  • Stream an object that either delivers data to
    its destination (screen, file, etc.) or that
    takes data from a source (keyboard, file, etc.)
  • it acts as a buffer between the data source and
    destination
  • Input stream a stream that provides input to a
    program
  • Output stream a stream that accepts output from
    a program
  • System.out is an output stream
  • System.in is an input stream
  • A stream connects a program to an I/O object
  • System.out connects a program to the screen
  • System.in connects a program to the keyboard

6
Binary Versus Text Files
  • All data and programs are ultimately just zeros
    and ones
  • each digit can have one of two values, hence
    binary
  • bit is one binary digit
  • byte is a group of eight bits
  • Text files the bits represent printable
    characters
  • one byte per character for ASCII, the most common
    code
  • for example, Java source files are text files
  • so is any file created with a "text editor"
  • Binary files the bits represent other types of
    encoded information, such as executable
    instructions or numeric data
  • these files are easily read by the computer but
    not humans
  • they are not "printable" files
  • actually, you can print them, but they will be
    unintelligible
  • "printable" means "easily readable by humans when
    printed"

7
Text File I/O
  • Important classes for text file output (to the
    file)
  • PrintWriter
  • FileOutputStream
  • Important classes for text file input (from the
    file)
  • BufferedReader
  • FileReader
  • Note that FileOutputStream and FileReader are
    used only for their constructors, which can take
    file names as arguments.
  • PrintWriter and BufferedReader cannot take file
    names as arguments for their constructors.
  • To use these classes your program needs a line
    like the following
  • import java.io.

8
Text File Output
  • Binary files are more efficient for Java, but
    text files are readable by humans
  • so occasionally text rather than binary files are
    used
  • Java allows both binary and text file I/O
  • To open a text file for output connect a text
    file to a stream for writing
  • create a stream of the class PrintWriter and
    connect it to a text file
  • For example
  • PrintWriter outputStream new PrintWriter(new
    FileOutputStream("out.txt"))
  • Then you can use print and println to write to
    the file
  • The text lists some other useful PrintWriter
    methods

9
TextFileOutputDemoPart 1
outputStream would not be accessible to the rest
of the program if it were declared inside the
try-block
  • public static void main(String args)
  • PrintWriter outputStream null
  • try
  • outputStream
  • new PrintWriter(new
    FileOutputStream("out.txt"))
  • catch(FileNotFoundException e)
  • System.out.println("Error opening the file
    out.txt.")
  • System.exit(0)

Opening the file
Creating a file can cause the FileNotFound-Excepti
on if the new file cannot be made.
10
TextFileOutputDemoPart 2
  • System.out.println("Enter three lines of text")
  • String line null
  • int count
  • for (count 1 count lt 3 count)
  • line SavitchIn.readLine()
  • outputStream.println(count " " line)
  • outputStream.close()
  • System.out.println("... written to out.txt.")

Writing to the file
Closing the file
The println method is used with two different
streams outputStream and System.out
11
Text File Input
  • To open a text file for input connect a text
    file to a stream for reading
  • use a stream of the class BufferedReader and
    connect it to a text file
  • use the FileReader class to connect the
    BufferedReader object to the text file
  • For example
  • BufferedReader inputStream
  • new BufferedReader(new FileReader("data.txt"))
  • Then
  • read lines (Strings) with readLine
  • BufferedReader has no methods to read numbers
    directly, so read numbers as Strings and then
    convert them
  • read a char with read

12
Testing for End of File in a Text File
  • There are several ways to test for end of file.
    For reading text files in Java you can use this
    one
  • Test for a special character that signals the
    end of the file
  • When readLine tries to read beyond the end of a
    text file it returns the special value null
  • so you can test for null to stop processing a
    text file
  • read returns -1 when it tries to read beyond the
    end of a text file
  • the int value of all ordinary characters is
    nonnegative
  • Neither of these two methods (read and readLine)
    will throw an EOFException.

13
Example Using Null toTest for End-of-File in a
Text File
Excerpt from TextEOFDemo
When using readLine test for null
When using read test for -1
13
Chapter 9
Java an Introduction to Computer Science
Programming - Walter Savitch
14
Binary File I/O
  • Important classes for binary file output (to the
    file)
  • DataOutputStream
  • FileOutputStream
  • Important classes for binary file input (from the
    file)
  • DataInputStream
  • FileInputStream
  • Note that FileOutputStream and FileInputStream
    are used only for their constructors, which can
    take file names as arguments.
  • DataOutputStream and DataInputStream cannot take
    file names as arguments for their constructors.
  • To use these classes your program needs a line
    like the following
  • import java.io.

15
When Using DataOutputStreamto Output Data to
Files
  • The output files are binary and can store any of
    the primitive data types (int, char, double,
    etc.) and the String type
  • The files created can be read by other Java
    programs but are not printable
  • The Java I/O library must be imported by
    including the lineimport java.io.
  • it contains DataOutputStream and other useful
    class definitions
  • An IOException might be thrown

16
Handling IOException
  • IOException cannot be ignored
  • either handle it with a catch block
  • or defer it with a throws-clause
  • We will put code to open the file and write to it
    in a try-block and write a catch-block for this
    exception
  • catch(IOException e)
  • System.out.println("Problem with output..."

17
Opening a New Output File
  • The file name is given as a String
  • file name rules are determined by your operating
    system
  • Opening an output file takes two steps
  • 1. Create a FileOutputStream object associated
    with the file name String
  • Connect the FileOutputStream to a
    DataOutputStream object
  • This can be done in one line of code

18
Writing a boolean Value to a File
  • boolean values can be either of two values, true
    or false
  • true and false are not just names for the values,
    they actually are of type boolean
  • For example, to write the boolean value false to
    the output file
  • outputStream.writeBoolean(false)

19
Closing a File
  • An output file should be closed when you are done
    writing to it (and an input file should be closed
    when you are done reading from it).
  • Use the close method of the class PrintWriter
    (BufferedReader also has a close method).
  • For example, to close the file opened in the
    previous example
  • outputStream.close()
  • If a program ends normally it will close any
    files that are open

20
Using Path Names
  • Path namegives name of file and tells which
    directory the file is in
  • Relative path namegives the path starting with
    the directory that the program is in
  • Typical UNIX path name
  • /user/smith/home.work/java/FileClassDemo.java
  • Typical Windows path name
  • D\Work\Java\Programs\FileClassDemo.java
  • When a backslash is used in a quoted string it
    must be written as two backslashes since
    backslash is the escape character
  • "D\\Work\\Java\\Programs\\FileClassDemo.java"
  • Java will accept path names in UNIX or Windows
    format, regardless of which operating system it
    is actually running on.

21
SummaryPart 1
  • Text files contain strings of printable
    characters they look intelligible to humans when
    opened in a text editor.
  • Binary files contain numbers or data in
    non-printable codes they look unintelligible to
    humans when opened in a text editor.
  • Java can process both binary and text files, but
    binary files are more common when doing file I/O.
  • The class DataOutputStream is used to write
    output to a binary file.

22
SummaryPart 2
  • The class DataInputStream is used to read input
    from a binary file.
  • Always check for the end of the file when reading
    from a file. The way you check for end-of-file
    depends on the method you use to read from the
    file.
  • A file name can be read from the keyboard into a
    String variable and the variable used in place of
    a file name.
  • The class File has methods to test if a file
    exists and if it is read- and/or write-enabled.

23
Window Interfaces Using Swing Objects
  • Event-Driven Programming and GUIs
  • Swing Basics and a Simple Demo Program
  • Layout Managers
  • Buttons and Action Listeners
  • Container Classes
  • Text I/O for GUIs

24
Event-Driven Programming
  • Programs with GUIs often use Event-Driven
    Programming
  • Program waits for events to occur and then
    responds
  • Examples of events
  • Clicking a mouse button
  • Dragging the mouse
  • Pressing a key on the keyboard
  • Firing an eventwhen an object generates an event
  • Listenerobject that waits for events to occur
  • Event handlermethod that responds to an event

25
Notes on the Simple Demo Program
import javax.swing. public class
FirstSwingDemo public static final int WIDTH
300 public static final int HEIGHT 200
public static void main(String args)
JFrame myWindow new JFrame()
myWindow.setSize(WIDTH, HEIGHT) JLabel
myLabel new JLabel(Please dont)
myWindow.getContentPanel().add(myLabel)
WindowDestroyer myListener new
WindowDestroyer() myWindow.addWindowListener(
myListener) myWindow.setVisible(true)
Used in all Swing programs
Creates a JFrame window named myWindow
Adds a label to the JFrame windownote use of
getContentPane
26
Methods of the JFrame Class
  • JFrame(String title)
  • constructor for creating a JFrame with a title
  • Container getContentPane()
  • returns the content pane of the JFrame, which has
    the add method for adding components
  • void setBackgroundColor(Color c)
  • void setForegroundColor(Color c)
  • void setSize(int width, int height)
  • void setVisible(boolean b)
  • void show()
  • sets visible and brings to front

27
Layout Managers
  • Layout Manageran object that decides how
    components will be arranged in a container
  • Used because containers can change size
  • Some types of layout managers
  • BorderLayout
  • FlowLayout
  • GridLayout
  • Each type of layout manager has rules about how
    to rearrange components when the size or shape of
    the container changes.

28
Buttons and ActionListeners
  • Basic steps for using a button in a Swing
    program
  • Create a Button object
  • Add the Button object to a container
  • Create an ActionListener object that has an
    actionPerformed method
  • Register the listener for the Button object
  • The following slides show an example of each step.

29
Create a Button Object andAdd the Button to a
Container
  • JButton stopButton new JButton(Red)
  • contentPane.add(stopButton)

String that will appear on the button
JButton is a predefined Swing class for buttons.
This example uses the Flow Layout so the add
method needs only one parameter.
The button will be added to this container.
30
Create an ActionListener Object
  • Make a class into an ActionListener
  • Add the phrase implements ActionListener to the
    beginning of the class definition
  • Define a method named actionPerformed

public class ButtonDemo extends JFrame
implements ActionListener . . .
public void actionPerformed(ActionEvent e)
. . .
31
The actionPerformed Method
  • An actionPerformed method must have only one
    parameter
  • The parameter must be of type ActionEvent
  • The parameter can be used to find the command for
    the ActionEvent

public void actionPerformed(ActionEvent e) if
(e.getActionCommand().equals(Red)) . . .
32
Register the Listener for the Button Object
  • If a button has no listener registered for it,
    there will be no response when the user clicks on
    the button.
  • An example of registering a listener for a
    button

JButton stopButton new JButton(Red) stopButto
n.addActionListener(this) contentPane.add(stopBut
ton)
this refers to the object that includes this code
in a method. In this example the object is a
JFrame class that implements ActionListener.
33
Container Classes
  • A container class can have components added to
    it.
  • Every Swing container class has an add method.
  • Some commonly used container classes are
  • JPanel
  • Container
  • Content pane of a JFrame

34
Hierarchy ofSwing Classes
Object
Component
AWT
Container
Class
Layout manager classes are in the AWT.
Window
Abstract Class
Frame
Swing
JFrame
JComponent
AbstractButton
JPanel
JLabel
JMenuBar
JMenuItem
JButton
JTextComponent
JMenu
JTextField
JTextArea
35
Text I/O for GUIs
  • Text fields and text areas
  • getText method retrieves text in component
  • setText changes text in component
  • If memo1 is a String and theText is either a
    JTextField or a JTextArea, then you could write

memo1 theText.getText() theText.setText(Hi
Mom)
36
Inputting and Outputting Numbers
  • To get an int from a TextArea or TextField
  • Get a String using getText
  • Trim extra white space using trim
  • Convert the String to an int using parseInt
  • int n Integer.parseInt(field.getText().trim())
  • To put an int into a TextArea or TextField
  • Convert the int to a String using toString
  • Put the String in the text component using
    setText
  • field.setText(Integer.toString(total))

37
Summary
  • GUIs (Graphical User Interfaces) are programmed
    using event-driven programming
  • The class JFrame is used to create a windowing
    GUI
  • A button is an object of class JButton
  • The add method of a container can be used to add
    components to the container
  • Comonents are added to the content pane of a
    JFrame rather than directly to the JFrame
  • A panel is a container object that is used to
    group components inside of a larger container
  • Text fields and text areas are used for text
    input and output in a GUI constructed with Swing

38
Javadoc and Java Style
  • Understand tags _at_author, _at_date, etc.
  • Understand single line comments, block comments,
    and javadoc comments
  • Understand where and how to use whitespace
  • Understand where and how to capitalize names

39
Javascript
  • Understand how to display text and buttons
  • Understand how to use simple mouse gestures
Write a Comment
User Comments (0)
About PowerShow.com