Integer Class library - PowerPoint PPT Presentation

1 / 156
About This Presentation
Title:

Integer Class library

Description:

used to convert a String to an int. Parse to 'extract' ... Integer find an integer in a string (e.g. xxx100xxx), and extract it (e.g. 100) ... – PowerPoint PPT presentation

Number of Views:157
Avg rating:3.0/5.0
Slides: 157
Provided by: cseBu
Category:

less

Transcript and Presenter's Notes

Title: Integer Class library


1
Integer Class library
  • convert to and from integers
  • used to convert a String to an int.
  • Parse to extract
  • Parse to Integer find an integer in a string
    (e.g. xxx100xxx), and extract it (e.g. 100).
  • int x
  • String UserInput 14 // readable 14
  • x Integer.parseInt( UserInput )

2
Calling a library method
4
1
2
  • return libraryClass.method ( send )
  • 1 - a collection of classes
  • 2 - a particular method in that class
  • 3 - a value sent to the method
  • 4 - the result of the methods work
  • in the example below
  • a string is sent, and an integer is returned
  • x Integer.parseInt( UserInput )

3
3
String libraries
  • Convert an int to a String (the other way)
  • String y
  • int x
  • y String.valueOf( x )
  • // x is an int, y is a String
  • remember
  • return library.method ( send )

10000s of such methods
4
Why is String capitalized, and int not?
  • String is a class Library
  • int is not a class Library
  • Integer.parseInt - Integer is a class Library
  • JOptionPane is a class Library
  • boolean is not
  • double is not
  • String.valueOf - class Libraries have methods

5
the Java keyword null
  • It means, literally, nothing
  • Has no value
  • Used as a placeholder before something is given a
    legitimate value.
  • Most uninitialized variables have a null value.

6
JOptionPane
  • Pane, not pain like a window pane
  • Puts a standard message box on-screen
  • import javax.swing.JOptionPane
  • UserInput JOptionPane.showInputDialog("Enter x
    ")
  • An on-screen message is sent.
  • A string is returned.

7
A simple Message Box
  • JOptionPane.showMessageDialog (null, "Welcome to
    the CSE 116 demo")
  • null is a necessary placeholder for
    showMessageDialog
  • will be used later to specify where to place
    Message
  • if null, then it shows up on your screen

Welcome to the CSE 116 demo
8
Use instead of System.out.println
  • int x 10
  • JOptionPane.showMessageDialog(null,"X " x )

9
(No Transcript)
10
A simple Yes/No/Cancel box
  • Int2 JOptionPane.showConfirmDialog
  • (null, "Do you really want to Exit?")
  • Returns an int
  • Int2 0 means Yes
  • Int2 1 means No
  • Int2 2 means Cancel

11
String Helper Methods
  • String userInput, Str1, Str2, Str3
  • int Int1, Int2
  • Str2 userInput.toLowerCase( )

12
String Helper Methods
  • Str2 Str1.toUpperCase( )

13
String helper methods
  • Str1 "x"
  • Int1 Str1.compareTo("x")
  • 0
  • Int1 Str1.compareTo("a")
  • 23
  • Int 1 Str1.compareTo("z")
  • - 2

14
String Helper Methods
  • Int2 Str1.indexOf("X")
  • The place of X in the string
  • - 1 if X not there

15
Setting up a dowhile
  • boolean quitFlag false
  • do
  • while (quitFlag false)

16
Continuing a dowhile
  • do
  • Str1 JOptionPane.showInputDialog(G to GoOn, or
    x to eXit")
  • Str2 Str1.toUpperCase( )
  • Int1 Str2.indexOf("X")
  • if (Int1 ! -1) // there's an x somewhere
  • quitFlag true
  • continue // go to the end of THIS
    loop
  • while (quitFlag false)

jumps directly to while
17
A simple Yes/No/Cancel box
  • Int2 JOptionPane.showConfirmDialog
  • (null, "Do you really want to Exit?")
  • Returns an int
  • Int2 0 means Yes
  • Int2 1 means No
  • Int2 2 means Cancel

18
The Outermost Loop
  • do
  • // program runs forever
  • while( true )

19
loops within loops
  • do
  • continue
  • do
  • continue
  • while ( quitFlag false )
  • while ( true )

20
  • // header
  • public class Lab1MainClass
  • public int y
  • public static void main(String args )
  • int x
  • supportMethod( )
  • // end main method
  • public static supportMethod( )
  • // end supportMethod
  • // end Lab1MainClass

class definition shared variables main
method not-shared method call support
method note end brackets
21
  • // header
  • import java.util.Random
  • public class Lab1MainClass
  • public int y
  • public Random myGen
  • public static void main(String args )
  • int x
  • myGen new Random()
  • // end Lab1MainClass

library shared variables
? ?
22
Instantiation
  • You or someone else writes a class
  • public class someClass
  • ..
  • You use the class in your program
  • You must make a local copy
  • someClass myObject new someClass( )
  • Or, two-step
  • public someClass myObject
  • myObject new someClass()

23
What is a class?
  • A program, with no main
  • Contains useful methods and variables, that you
    might want to use in your program, that HAS a
    main.

24
Applications - The main Method
  • The computer runs it, you dont.
  • The computer calls the main method
  • The main method uses methods, contained in
    Objects, derived from Classes that you write.

25
  • public static void main(String args)
  • ShowColors app new ShowColors( )
  • // any method in ShowColors is now useable
  • // as app.MethodName( )

26
Three ways to make use of classes
  • One step instantiation
  • JFrame myWindow new JFrame( )
  • Two step Instantiation
  • public JFrame myWindow
  • public static void method( int a)
  • myWindow new JFrame( )

27
third way
  • public class myClass extends JFrame
  • // your class inherits all of JFrames
  • // methods

28
Use these helper libraries
  • import javax.swing.JFrame // for JFrame
  • import java.awt. // for painting and animation
  • import java.awt.event. // for event
    handling, more later
  • import java.util.Random // always useful

29
some JFrame methods
  • setLocation(100,200)
  • setSize(250,250)
  • setVisible(true)
  • getContentPane( ) // gives us a context
  • // more later
  • setDefaultCloseOperation( EXIT_ON_CLOSE)

30
If you dont extend JFrame.
  • public class MainClass
  • public MainClass ( )
  • JFrame myFrame new JFrame( )
  • myFrame.setLocation(100,200)
  • myFrame.setSize(250,250)
  • myFrame.setVisible(true)
  • // end MainClass constructor
  • public static void main (String args)
  • MainClass application new MainClass( )
  • // end main method
  • // end class

31
Color class
  • Like the String class, and Integer class, does
    not use the new keyword.
  • holds a color value (nothing more)
  • e.g Color boxColor new Color( )
  • boxColor Color.blue
  • or
  • Color boxColor Color.blue
  • then boxColor can be used to set System
    properties in Classes/Objects that need color
    (more later).

32
JColorChooser returns a Color object to the
caller
33
Returns an Object?
  • JColorChooser fills in all of the information in
    a blank object of the Color class, and copies it
    to the Color object in the calling statement
  • boxColor JColorChooser.showDialog(
  • null, Greeting, default color )

34
the this qualifier
  • Means this object, the one that were in.
  • Used when a call to a method, especially in a
    child, needs to specify which object the method
    should act upon.
  • this always refers to an object of some type.

35
the super qualifier
  • refers to the parent class
  • the command super calls the parents constructor
  • super.MethodName can call any method in the
    parent.

36
A Random Number generator
  • import java.util.Random
  • .
  • .
  • .
  • Int X 0
  • Random myGen new Random( )
  • X myGen.nextInt( 50 )

37
The paint Method
  • Computer runs it once (you dont), but then you
    can run it by calling repaint().
  • The computer passes it an object of the Graphics
    Class, of its own making.

38
  • public void paint (Graphics g)
  • // the computer calls the paint program
  • // automatically whenever an event requires
  • // the screen to be redrawn

39
Graphics!
  • g.setColor
  • g.fillRect
  • g.drawString
  • g.drawPolygon
  • hundreds of methods that use your computers
    graphics capability

40
demo
  • A Frank Lloyd Wright style generator

41
the Container class
  • Holds a whole window context frames, scroll
    bars, buttons, menus, pop-ups, and operator
    actions mouse clicks, dragging dropping.
  • Operator actions are called events.
  • JFrame objects must be placed in a container, to
    be of any use.
  • ContentPane is a special container that
    contains the current state of the computer.

42
Creating a ContentPane container
  • Container frameContainer new Container()
  • frameContainer getContentPane( )
  • frameContainer is now an event environment,
    which is an object that holds the current details
    of all screen, user, keyboard, mouse events and
    conditions, and further... is a place where we
    can build a GUI, compatible with the computers
    configuration (called a layered glass pane).

43
what does this do?
  • FlowLayout layout new FlowLayout( )
  • Container frameContainer new Container()
  • frameContainer getContentPane( )
  • frameContainer.setLayout( layout )

JFrame
Container
44
more JFrame and Container methods
  • setSize( w, h )
  • setLocation( x, y )
  • setDefaultCloseOperation( EXIT_ON_CLOSE )
  • Container myPC new Container()
  • myPC getContentPane()
  • FlowLayout layout new FlowLayout()
  • myPC.setLayout( layout )
  • JButton helloButton new JButton( "Hello" )
  • myPC.add( helloButton )
  • setVisible( true )

45
  • int z myGen.nextInt( 7 ) // 0 - 6
  • if (z 0)
  • return(Color.red)
  • else if (z 1)
  • return( Color.blue)
  • else if (z 2)
  • return( Color.cyan)
  • else if (z 3)
  • return( Color.green)
  • else if (z 4)

46
  • public Color getColor()
  • int z myGen.nextInt( 7 )
  • switch(z)
  • case(0)
  • return(Color.red)
  • case(1) return(Color.blue)
  • case(2) return(Color.cyan)
  • case(3) return(Color.green)
  • case(4) return(Color.magenta)
  • case(5) return(Color.yellow)
  • default return(Color.pink)

47
Arrays
  • A difficult concept at first int z5
  • Means z0, z1 , z2, z3, z4 are
    separate integer variables
  • Starts at 0.
  • An array with 5 elements is indexed from 0 to 4.
  • in Java int z new int5

48
Shortcut for defining arrays
  • int xValues 1, 4, 6, 9, 0
  • Defines an array of 5 integers called xValues
  • xValues4 0

49
For polygons
  • int xValues 20, 40, 50, 30, 20, 15
  • int yValues 50, 50, 60, 80, 80, 60
  • Polygon polygon1
  • new Polygon(xValues, yValues,
    6)
  • g.drawPolygon( polygon1 )
  • is needed to draw a single, closed, 6-sided
    polygon, and defines the x,y points (20,50)
    (40,50) (50,60) (30,80) and (15,10).
  • See how they match up?

50
( x 50, y 0)
( x 0, y 100)
( x 100, y 100)
int xValues 50, 0, 100 int yValues
0, 100, 100 Polygon polygon1 new
Polygon(xValues, yValues, 3) g.setColor(
Color.cyan ) g.drawPolygon(polygon1)
51
The Font class
  • Constructor
  • Font ( Name, Style, Size )
  • Name Monospace, Arial, Helvetica
  • Style uses FIELDS
  • Font.BOLD, Font.PLAIN, Font.ITALIC
  • Font myFont new Font(Arial, Font.PLAIN,12 )

52
Writing text in Graphics
  • Font is an object like Color
  • Font myFont new Font ("Monospaced",
  • Font.BOLD , 12)
  • g.setFont( myFont )
  • g.setColor( Color.red)
  • g.drawString( hello" ,160, 220)

53
A push-button object
  • JButton helloButton new JButton( "Hello" )
  • Where can we place the pushbutton?
  • On anything, really remember that!

54
JFrame methods summary
  • setSize (400, 400)
  • setLocation (50, 75)
  • setDefaultCloseOperation( EXIT_ON_CLOSE )
  • setVisible( true )
  • NOT a JFrame method
  • add( someObject ) a Container method

55
Graphics method summary
  • paint (Graphics g)
  • g.setColor( boxColor )
  • g.fillArc( x, y, width, height, 0, 360 )
  • g.fillRect( x, y, width, height )
  • g.setFont( myFont )
  • g.drawString( hello" ,160, 220 )
  • g.drawPolygon( shape1 )
  • g.drawLine( x1,y1,x2,y2)

56
Using Layout Managers
  • A layout manager is an object that determines the
    size and position of the components within a
    container. Although components can provide size
    and alignment hints, a container's layout manager
    has the final say on the size and position of the
    components within the container.

57
Flow Layout
  • Container myPC new Container()
  • myPC getContentPane()
  • FlowLayout layout new FlowLayout()
  • myPC.setLayout( layout )
  • JButton helloButton new JButton( "Hello" )
  • myPC.add( helloButton )

58
Grid Layout
  • Container myPC new Container()
  • myPC getContentPane()
  • GridLayout layout new GridLayout()
  • myPC.setLayout( layout )
  • JButton helloButton new JButton( "Hello" )
  • myPC.add( helloButton )

59
Border Layout
  • Container myPC new Container()
  • myPC getContentPane()
  • BorderLayout layout new BorderLayout()
  • myPC.setLayout( layout )
  • JButton helloButton new JButton( "Hello" )
  • myPC.add( helloButton, BorderLayout.NORTH )

60
first an Integer object
  • old way
  • int x 10
  • new way
  • Integer x new Integer( 10 )
  • Integer is a container that holds ints, but has
    methods to operate on them (more powerful)
  • int is just a number safe in most cases

An OBJECT!
of this CLASS!
61
JButton
  • Create
  • JButton pushButton new JButton(Java )
  • Add to Container
  • myPC.add( pushButton )
  • Use
  • - not so easy
  • - cant really know when user presses it

An OBJECT!
of this CLASS!
62
Instantiate a Class into an Object when there are
methods to be used.
  • Container myPC new Container( )
  • FlowLayout layout new FlowLayout( )
  • JButton pushButton new JButton(push )
  • myPC.setLayout ( layout )
  • myPC.add( pushButton )

63
JSlider
  • Create
  • JSlider slide new JSlider( )
  • Add
  • myPC.add( slide )
  • Use
  • int value slide.getValue()
  • Or
  • int x 10
  • slide.setValue( x ) // uses ints

how do you know when user changes it?
64
JProgressBar
70
  • Create
  • JProgressBar percent new JProgressBar( )
  • Add
  • myPC.add( percent )
  • Use
  • percent.setValue( somenumber ) // uses ints

An OBJECT!
of this CLASS!
provides METHODS
65
JSpinner
  • Create
  • JSpinner dial new JSpinner( )
  • Add
  • myPC.add( dial )
  • Use
  • int value dial.getValue()
  • Or
  • Integer x new Integer( 10 ) // NO ints
  • dial.setValue( x )

how do you know when user changes it?
66
Asynchronous events
  • We can put controls on screen
  • We can setValues
  • We can getValues in the constructor
  • But how do we get values that the operator
    changes, since we cant keep looking all the time
  • Events are called asynchronous when you cant
    tell when they will happen

67
Polling
  • One sloppy way to tell when something changes, is
    by looking at it over and over
  • do
  • System.out.println( dial.getValue( ) )
  • while(true)

68
A better way
  • Listen, in the background
  • Java supports listeners
  • ActionListener

69
JButtons
An Event Java code that Listens for an
event Is called an Action Listener
70
3 new classes
  • Use these two
  • ActionEvent
  • ActionListener
  • To write your own
  • eventClass with actionPerformed( ) method

71
Add this to any code
  • private class eventClass implements
    ActionListener
  • public void actionPerformed ( ActionEvent e )
  • System.out.println(Something just
    happened)
  • System.out.println( e.getActionCommand( )
    )

72
What does implement mean
  • Just like extend, only different.
  • In extend, you can choose to use as-is, or
    re-write the methods of the parent class.
  • The author of a class that is implemented,
    insists that YOU write the methods for it.

73
ActionListener class
  • An interface written by someone else, and you
    must adhere to the contract
  • Class that implements the ActionListener must
    meet one obligation
  • provide a method called actionPerformed that
    receives an ActionEvent object, as a means of
    telling what just happened?.
  • The actionPerformed method runs based on a
    certain specified asynchronous event

74
Add this to any code
  • private class eventClass implements
    ActionListener
  • public void actionPerformed ( ActionEvent e )
  • System.out.println(Something just
    happened)
  • System.out.println( e.getActionCommand( )
    )

75
Objects of eventClass
  • Useful when this becomes an object somewhere in
    the immediate code (for instance, a class
    constructor)
  • eventClass handler new eventClass( )

76
the JButton
  • grabs one ActionListener object as its own
  • (e.g. handler)
  • sends its activity to that ActionListener

77
Tying a component to an ActionListener
  • Components JButtons, JComboBoxes, JTextFields,
    and other GUI controls.
  • JButton helloButton new JButton( Hello)
  • eventClass handler new eventClass( )
  • helloButton.addActionListener( handler )

78
Inner Classes
  • the eventClass implementation of the
    ActionListener interface class, is wholly defined
    as private within the bounds of your main class
  • public class ButtonTest extends JFrame
  • private class eventClass implements
    ActionListener
  • public void actionPerformed ( ActionEvent
    e )

79
  • import java.awt.event.
  • public class ButtonTest extends JFrame
  • public ButtonTest ( )
  • private class eventClass implements
    ActionListener
  • public void actionPerformed ( ActionEvent
    e )
  • public static void main (String args)

JFrame class
Constructor
Inner class
main method
80
Combo boxes ItemEvents not ActionEvents
  • // inner class for combo item handling
  • private class ComboHandler implements
    ItemListener
  • public void itemStateChanged( ItemEvent x )
  • System.out.println( x.getItem( ) )
  • // end inner class

81
in Constructor
  • String names "stay", "leave", "ignore"
  • JComboBox myCombo new JComboBox( names )
  • c.add( myCombo)
  • ComboHandler myComboHandler new ComboHandler(
    )
  • myCombo.addItemListener(myComboHandler)

82
Labels no handler
  • JLabel label3 new JLabel(Demo)
  • c.add(label3)

83
e.getSource
  • Pull JButtons, JTextFields out of constructor
    brackets.
  • Make them public and known to every one.
  • Can be tested in if statements
  • Must use the two step instantiation

84
Two-step Instantiation
  • public class ButtonTest extends JFrame
  • JButton exitButton
  • public ButtonTest()
  • exitButton new JButton(I want to leave)
  • // other stuff

85
test in actionPerformed
  • private class ButtonHandler implements
    ActionListener
  • public void actionPerformed( ActionEvent e
    )
  • System.out.println(e.getActionCommand())
  • if (e.getSource( ) exitButton)
  • System.out.println("Exiting")
  • System.exit(0)

86
4 problems to solve
  • Formatting a Date( ) for Month, Year only
  • Forcing button layout on a JFrame (when the
    layout manager is no help)
  • Determining which component caused an event
  • JButton Colors

87
import java.util.Date public class testpublic
test() System.out.println("Starting
test program") Date myDate new Date()
System.out.println( myDate ) public
static void main(String args ) test app
new test( )
88
DateFormat class
  • import java.util. // for Date
  • import java.text. // for DateFormat
  • public class shortDate
  • public static void main(String args)
  • Date myDate new Date()
  • DateFormat df DateFormat.getDateInstance()
  • String todaysDate df.format( myDate )
  • System.out.println( todaysDate )

89
Sub-layouts
  • Add buttons to a JPanel
  • JButton exitButton new JButton(Exit)
  • JPanel topRow new JPanel()
  • topRow.add( exitbutton )
  • Add JPanel to the container
  • c.add( topRow )

90
e.getSource
  • e.getActionCommand gets the button label
  • What if the event is caused by a component that
    has no label (like a Timer)?
  • e.getSource( ) returns the component object
  • So all components must be public.

91
JButton Colors
  • JButton exitButton new JButton(Exit)
  • exitButton.setBackground( Color.red )

92
Two types of handlers
  • An ActionListener for most components
  • private class eventClass implements
    ActionListener public void
    actionPerformed ( ActionEvent e )
  • An ItemListener for comboBoxes
  • private class itemClass implements ItemListener
    public void itemStateChanged( ItemEvent x )

93
A Timer Event
  • Imagine a clock ticking at every tick, the
    computer generates an event.
  • Computers have many internal clocks.
  • Some with nano-second timing.
  • 10-9
  • A nanosecond is to a second as a second is to 30
    years
  • The standard measure of computer time is the
    millisecond - 10-3

94
Time
  • second
  • millisecond - 1/1000 - 10-3
  • microsecond - 1/1,000,000 - 10-6
  • nanosecond - 1/1,000,000,000 - 10-9

95
The Timer Component
  • SomeHandler myHandler new SomeHandler( )
  • Timer tickTimer new Timer(1000, myHandler)
  • tickTimer.start()
  • tickTimer.stop()

How many milliseconds between events
what code runs every tick
96
Animation Coding Example
97
Main Class
  • public class Bouncer extends JFrame
    implements ActionListener
  • // note that the main class IS the handler class
  • // any registration will use this
  • // will contain an actionPerformed method

98
Main Class continued
  • private Timer timer // timer must be known
    everywhere in the // class
  • int ballX0
  • int ballY0
  • int diameter 50
  • static int width 400
  • static int height 400
  • int counter 0
  • // NO CONSTRUCTOR (everything must be in main
    method)

99
paint method
  • public void paint (Graphics g)
  • // background
  • g.setColor( Color.white )
  • g.fillRect( 0,0, width, height)
  • // ball
  • g.setColor( Color.red )
  • g.fillOval( ballX, ballY, diameter, diameter
    )

100
actionPerformed every time the timer ticks
  • public void actionPerformed(ActionEvent e)
  • ballY
  • ballX
  • repaint( ) // like calling the paint method
  • if ( counter 400 ) // inc. and test
    together
  • timer.stop( )

101
main does what constructor usually does
  • public static void main(String args)
  • diameter 50
  • bouncer ball new bouncer( )
  • ball.setSize( 400, 400 )
  • ball.setVisible( true )
  • ball.setDefaultCloseOperation( EXIT_ON_CLOSE
    )
  • timer new Timer( 10, ball )
  • timer.start( ) // end main method

102
add a bounce
  • public void actionPerformed(ActionEvent e)
  • ballY
  • ballX
  • repaint( )
  • if(counter 400)
  • timer.stop()
  • if(counter 200)
  • ballY ballY - 2 // net effect -1

103
Advice on Methods 10 Useful Items
  • Using static classes

104
So whats a static class?
  • Its a class that doesnt have to be instantiated
    to be used
  • Like System.exit(0)
  • Like Math.random()

105
1. Math.round(x)
  • double x 47.67
  • Math.round( x ) returns an int, rounded to 48
  • Use (int) x to truncate

106
2. String.valueOf( any number )
  • creates a String when you need it

107
3. Integer.parseInt( any String )
  • creates an int from a String

108
4. Double.parseDouble( any String )
  • creates a double from a String

109
5. x.substring( start, end )
  • String x Happy Halloween
  • x.substring(2, 4) yields ppy
  • Start at 0.
  • x.substring( 11 ) yields ween from 11 to
    end
  • Also useful
  • x.equalsIgnoreCase( another String )
  • returns a boolean true if the same

110
6. Math.random( )
  • Returns a double value with a positive sign,
    greater than or equal to 0.0 and less than 1.0.

111
7. some other Math methods
  • Math.pow (double a, double b)           Returns
    the value of the first argument raised to the
    power of the second argument.
  • Math.sqrt( double a )           Returns the
    positive square root of a double value.
  • Math.max( a, b ) and Math.min( a, b )

112
8. JOptionPane
  • Here are three useful static methods from
    javax.swing.JOptionPane that allow you to easily
    create dialog boxes for input and output. The
    Java API documentation has many more JOptionPane
    options, but these are sufficient for many uses.
    In the code below userInput and text are Strings,
    button is an int.
  • String userInput  JOptionPane.showInputDialog(
    component, text )
  • JOptionPane.showMessageDialog( component, text )
  • int button JOptionPane.showConfirmDialog(
    component, text )
  • Use null for the component parameter if you don't
    have a window
  • The dialog box will be centered over the
    component given in the first parameter. Typically
    you would give the window over which it should be
    centered. If your program doesn't have a window,
    you may simply write null, in which case the
    dialog box will be centered on the screen.

113
9. Shortcuts
  • x is the same as x x 1
  • String userInput Hello
  • userInput how are you? yields
  • Hello how are you?
  • System.out.println(\nHello)
  • when printed, \n skips a line
  • System.out.print(Hello)
  • does not go to next line

114
10. A website
  • http//leepoint.net/notes-java/
  • I have no idea where this is from.

115
Exceptions
  • Protecting methods from errors
  • CATCHING an exception protects your program from
    bad users
  • THROWING an exception protects others who use
    your methods

116
catching an error
  • try
  • x Integer.parseInt( userString )
  • catch (Exception e)
  • System.out.println(Not an integer!)

117
trycatch
  • Tries the try-bracketed statement.
  • try
  • // whatever is here
  • Stops at an error. Does not complete.
  • Error info is placed into the object e, of the
    Exception class - can decipher ALL exceptions
  • catch (Exception e)
  • // do something here

118
Exception class
  • catch (Exception e)
  • declares an object e of the Exception class
  • there are methods to be used
  • catch (Exception e)
  • e.printStackTrace( ) // where the error was
  • System.out.println(user did e.getMessage(
    ) )
  • // what input
    caused error
  • System.out.println(computer thought
    e.toString( ) )
  • // the
    computers description of
  • // the
    message

119
Summary - Exception methods( )
  • catch (Exception e)
  • e.getMessage( ) - what the user typed that
    generated the error
  • e.toString( ) - the computers description of the
    message
  • e.printStackTrace( ) - list all the methods from
    main, to the one that generated the error

120
catch different types
  • try
  • myClass myObject new myClass()
  • myObject.myMethod( )
  • // method 2( )
  • // method 3( )
  • catch (NullPointerException e)
  • catch (DivideByZeroException e)
  • System.out.println(Cant divide by zero)

121
different types
  • Exception catches all
  • NullPointerException - method called in try, was
    supposed to return an object (like Color), but
    didnt (user hit cancel in JColorChooser)
  • ArrayIndexOutOfBoundsException - method called
    in try, accessed index greater than the array
    definition.

122
different types
  • NumberFormatException - method called in try,
    like parseInt, tried to convert a string to a
    number, and the string wasnt a digit.
  • ArithmeticException - method called in try, did
    something arithmetically wrong - like mixing
    variable types.

123
different types
  • AWTException - method called in try, attached a
    handler object that was inappropriate for the
    component (a MouseListener to a JButton, or an
    object not of an ActionListener class).
  • DivideByZeroException - method called in try, did
    a divide by zero.

124
throwing an exception
  • public myClass
  • public double myMethod( int q) throw
    DivideByZeroException
  • if (q 0)
  • throw new DivideByZeroException( )
  • else
  • return(10/q)

125
User Defined Exceptions
126
1. extending Exception
  • class HighTempException extends Exception
  • public HighTempException()
  • super(Temperature Exceeds Safe Level")

127
super gives us all the necessary methods
  • getMessage( ) - what the user typed that
    generated the error
  • toString( ) - the computers description of the
    message
  • printStackTrace( ) - list all the methods from
    main, to the one that generated the error

128
2. throwing
  • public void increasePowerLevel() throws
    highTempException
  • powerLevel powerLevel 10
  • temperature powerLevel 100
  • if (temperature 10000)
  • throw new highTempException()
  • // end increasePower

129
3. using (i.e. catching)
  • try
  • chernobyl.increasePowerLevel()
  • catch (highTempException hte)
  • hte.printStackTrace()
  • System.exit(0)

130
Managing Data
  • Databases
  • Arrays, Lists, and File I/O

131
An Array-based database
  • public static String Artist new String5
  • public static String Song new String5
  • public static int length 0
  • public static void main(String args)
  • length Artist.length
  • Artist0 "System of a Down"
  • Song0 "Hypnotize"
  • Artist1 "Every Time I Die"
  • Song1 "Kill the Music"
  • // etc

132
Whats wrong with this
  • Two arrays must be synchronized
  • Filling the arrays with Artists and Songs is done
    IN THE CODE. Bad.
  • One more thing.

133
Sorting
  • public static void sortByArtist()
  • for (int y 0 y
  • for (int z 0 z
  • if ( Artistz.compareTo(Artisty) 0 )
  • swap( y,z)
  • // end if
  • // end for z
  • // end for y
  • // end sort by artist

134
Swap permanently moves items
  • public static void swap( int a, int b)
    String temp temp Artista Artista
    Artistb Artistb temp temp Songa
    Songa Songb Songb temp

135
File Helper Classes
136
Class File
  • We want
  • String lineOfText
  • We start with
  • File fileObject
  • fileObject will contain tons of information on a
    file, BUT NOT ITS CONTENTS.

137
JFileChooser
138
Class JFileChooser - like JColorChooser
  • // 1. create a file object
  • File fileObject
  • // 2. create a file chooser
  • JFileChooser fileChooser new JFileChooser( )
  • // 3. show the file chooser
  • fileChooser.showOpenDialog( null )
  • // 4. attach the choice to the file object
  • fileObject fileChooser.getSelectedFile()

139
FileReader Class
  • File Class contains methods to get file info
  • FileReader class contains methods to get file
    contents
  • Too difficult to use, though. Have to deal with
    one character a time, rather than buffering up
    many characters into a String.
  • FileReader fileRead new FileReader(
    fileObject )

140
One last class Buffered Reader
  • FileReader fileRead new FileReader(
    fileObject )
  • BufferedReader textInput new BufferedReader(
    fileRead )
  • Contains a readLine() method!!! Also a ready()
    method. Also a close() method
  • Start with a file object
  • Create a FileReader object using the File object
  • Create a BufferedReader object using the
    FileReader object

141
BufferedReader finally gets to file contents
  • String lineOfText
  • FileReader fileRead new FileReader( fileObject
    )
  • BufferedReader textInput new BufferedReader(
    fileRead )
  • System.out.println("The file contents are")
  • while ( textInput.ready( ) true ) // more
    lines?
  • lineOfText textInput.readLine( )
  • System.out.println(lineOfText)
  • textInput.close( )
  • System.exit(0)

142
2 ways to create a file object
  • File musicFile
  • JFileChooser fileGetter new JFileChooser()
  • fileGetter.showOpenDialog( null )
  • musicFile fileGetter.getSelectedFile()
  • or
  • File f new File (filename.txt)

143
try territory
  • try FileReader fileContents new FileReader(
    musicFile ) BufferedReader textInput new
    BufferedReader( fileContents ) while
    (textInput.ready() true ) Artist
    i textInput.readLine() Song i
    textInput.readLine()
    textInput.readLine() i
    textInput.close()
  • catch( IOException e) System.out.println("No
    file")

144
Writing to a file
  • File f new File( "newfile.txt" )
  • try
  • FileWriter out new FileWriter( f )
  • BufferedWriter writer new BufferedWriter(
    out )
  • for (int x 0 x
  • writer.write( Artistx " " Songx
    )
  • writer.newLine( )
  • writer.close()
  • catch ( IOException e )
  • System.out.println(problem writing to file")

145
Threads
  • Our last topic
  • How do many programs run at once on the same
    computer?
  • What is meant by client / server?

146
what are threads?
  • independently running programs within one Unix
    process
  • can communicate through (static) variables that
    they share
  • define the Client / Server relationship
  • used when a task needs undivided attention
  • playing mp3s
  • running a task while waiting for user input

147
how threads operate
Server
main
.start
.run()
.start
communicate?
Client
.run()
148
main typically exists in the server
Server
main
.start
.run()
.start
Communicate usually through a separate class
Client
.run()
149
timeline
Server thread
?
main
end (not exit)
?
Client thread
150
writing a client thread
  • public class ClientClass extends Thread
  • public void run()
  • do while
  • // stuff
  • ( true )

151
writing a Server
  • public class ServerClass extends Thread
  • public void run()
  • while
  • // does stuff here
  • ( true )
  • // end run()
  • public static void main (String args)
  • ClientClass clientThread new ClientClass()
  • clientThread.start()
  • ServerClass serverThread new ServerClass()
  • serverThread.start()
  • // end main
  • // end class

152
your Server Class responsibility
  • main
  • start own thread
  • start all client threads
  • run forever until commanded to stop
  • System.exit(0) from this classs .run() ends all
    threads
  • actually any System.exit(0) ends all threads.
  • many ways to command - shared variables are often
    used files etc.

153
talk to each other
  • public class commClass
  • public static String ClientToServer "idle"
  • public static String ServerToClient "idle"
  • // end commClass
  • static means everyone can use the Strings
  • commClass.ClientToServer exit
  • defines a protocol

154
typical uses of thread communications
Server
e.g. web server
registration Ive started
display this page
mouse clicks new pages
Client
e.g. web page
155
some useful methods
  • Thread.sleep( milliseconds ) - suspends this
    threads activity

156
stopping a thread
  • a clean end to a threads .run( ) method ends
    that thread.
  • A .run( ) method that is in a while (true)
    loop will not end.
  • System.exit(0) from ANYWHERE ends all threads
Write a Comment
User Comments (0)
About PowerShow.com