Problem Solving with Data Structures using Java: A Multimedia Approach - PowerPoint PPT Presentation

1 / 77
About This Presentation
Title:

Problem Solving with Data Structures using Java: A Multimedia Approach

Description:

Problem Solving with Data Structures using Java: A Multimedia Approach Chapter 2: Introduction to Java What if we get it wrong? An example with Music import jm.util ... – PowerPoint PPT presentation

Number of Views:149
Avg rating:3.0/5.0
Slides: 78
Provided by: MarkGu
Category:

less

Transcript and Presenter's Notes

Title: Problem Solving with Data Structures using Java: A Multimedia Approach


1
Problem Solving with Data Structures using Java
A Multimedia Approach
  • Chapter 2 Introduction to Java

2
Chapter Objectives
  • Explain why Java is relevant to modeling and
    simulation.
  • Give the basic syntax details for variables,
    arrays, iteration, and conditionals.
  • Explain how to create a class and a subclass.
  • Give the user a brief introduction to the
    manipulation of pictures, sounds, and music.

3
Things to do to get started
  • Download and install JDK (Java Development Kit)
  • Download and install DrJava
  • Download JMusic
  • Download the Java source files for class
  • Then, tell Java where to find the JMusic and Java
    source files.

4
Parts of DrJava
List of class files that you have open
Text of your class file (.java)
Where you interact with Java
5
Java is object-oriented
  • 95 of everything in Java is an object.
  • In object-oriented programming, you care about
    more than just specifying the process.
  • You care about who (or what) does the process,
  • And how the overall process emerges from the
    interaction of different objects.

6
Object-oriented programming is about modeling and
simulation
  • The whole idea of object-oriented programming is
    to create a model of the part of the world (real
    or imaginary).
  • Creates constraints
  • The real world doesnt have one set of
    rules/steps.
  • You dont write one big program.
  • In the real world, no one knows everything, no
    one can do everything.
  • Each object has its own things it knows and
    things it can do.

7
Example A movie theater
  • Different jobs in the theater ticket-seller,
    ticket-taker, drink-seller, theater-cleaner.
  • Different skills for each.
  • Classes track what objects can do (methods) and
    know (fields).

8
Associations and Inheritance
  • All movie showings have-a (association) movie
    (with name and length), and a time.
  • Private showings have contact information, too
  • PublicShowing and PrivateShowing are subclasses
    (children) of MovieShowing.
  • This diagram represents that in UML.

9
Responsibility-Driven Design
  • Each object is responsible for knowing things and
    doing things appropriate to its type.
  • The title of the movie belongs with the movie,
    not with the movie showing.
  • You want to distribute responsibility across your
    objects to decrease complexity in programming.

10
Variables in Java know their types
  • Variables in Java know that kinds of things
    (values) they can hold.
  • Objects in Java are organized into classes.
  • A class specifies what all the objects of that
    class know and can do.
  • All pictures can show themselves, even though
    each picture is different.
  • Variables in Java are specific to particular
    classes.
  • We declare a variable to only hold objects of
    particular classes.

11
Declaring and setting variables with types
Int (integers) can only hold numbers without
decimal points
Variables values can be changed, but not
re-declared.
12
Other types char, boolean, float, double
  • gt char firstLetter a
  • gt System.out.println(firstLetter)
  • a
  • gt boolean flag true
  • gt System.out.println(flag)
  • True
  • gt float f 13.2f
  • gt f
  • 13.2
  • gt double d
  • gt d 13.231
  • gt d
  • 13.231
  • gt df
  • 26.43099980926514
  • gt af
  • Error Bad types in assignment
  • gt a(int) f
  • 13

13
Strings
14
What do strings know?Check the API!
  • Check the API at java.sun.com

15
Object and Primitive variables
  • Primitive variables (like the int a) reference
    memory associated with that name.
  • Object variables (like the String s) refer to an
    object reference, that points to the actual
    object.
  • Object variables can reference an object, or any
    child of the object.
  • The actual objects could have different fields,
    and thus, different memory sizes.

16
null, a special value
  • null is an object variable value that means
    doesnt refer to any object.
  • Its not zero, its not true, its not false.
  • Its just null.

17
Conditionals
  • IF ( EXPRESSION)
  • STATEMENT
  • IF (EXPRESSION)
  • STATEMENT
  • Else
  • STATEMENT

Can use curly braces to have more than statement
after IF.
18
Arrays
  • Declare an array with type , like Picture to
    create an array of pictures.

myArray.length here will be 4.
19
Iteration with FOR
  • FOR (type variable array)
  • STATEMENT

20
Iteration with FOR (part 2)
  • FOR (initial-expression
    continuing-condition
    iteration-expression)
  • STATEMENT

Incrementing variables is so common, theres a
shorthand.
21
Iteration with WHILE
  • WHILE (expression) STATEMENT

22
Strings are objects, not arrays of characters
  • Arrays of characters
  • Strings

23
Using Java to Model the World
  • Object-oriented programming is explicitly about
    creating a simulation of the world.
  • The classes in the program are meant to simulate
    kinds of things in the world.
  • The relationships between classes is meant to
    simulate relationships in the world.
  • The knowledge and behavior of instances are meant
    to simulate what real objects know and do.

24
Getting the level right
  • How much do you model?Answer Depends on what
    you care about.
  • Imagine a simulation of a vending machine.
  • Want to know how much force the can withstands
    when it hits the bottom? Better model height of
    the racks, weight of the cans, and gravity.
  • Want to know how purchases are processed? Then
    you want to model selections and sales
    transactions (and you can ignore gravity).

25
A Sample Model
  • Imagine that we want to model students in terms
    of how they register for classes (as opposed to
    what they eat, how they dont sleep, and how they
    gain the Freshman-15).
  • We care about students having names and
    identification numbers.
  • (We dont care about nutrition, metabolism, and
    exercise, then.)
  • But we dont want our Student class to have a
    name and an id, because Students dont have
    names. People do

26
A Student Model
  • Person is the general, superclass.
  • A Person has a name.
  • Student is a subclass of Person.
  • A Student has a student identification number
    (id).
  • Because Student inherits from Person, all methods
    and fields (or instance variables from Person
    exist in every instance of Student.
  • That is, Students have both names and ids.

27
Starting a Definition of Person
  • Any class can make instances from a public class.
  • A public field (the String name) can be accessed
    directly from any instance of Person.
  • A private field can only be accessed by the
    classs methods.
  • All fields are inherited in subclasses, even
    private ones, though only the superclasss
    methods can manipulate those fields

28
Using our new Person class
  • We create instances with new and the classname().
  • The variable fred has type Person, so it can hold
    an instance of Person.
  • The name initially has no value its null.

object.field references the field instance
variable in the object. object.method() executes
the method in the object.
29
Public Fields can be Changed Anywhere
  • Should we be able to tell the instance in Fred
    that its name is now Mabel?
  • Should names be changeable anywhere?

30
Definition 2 Making names private
setName() is void, because it doesnt return
anything.getName() returns a String.
  • Now name is private. It can only be changed with
    setName() and read with getName()

31
Trying out Definition 2
  • Should People have names as soon as they are
    created?

32
Definition 3 Using constructors
  • Constructors are called via Person(), to
    initialize an object.

33
Accessing Constructors
34
Discourse Rules for Java
  • Not syntax rules. Its just the way we talk in
    Java.
  • The sheriff in a Western says, Howdy! not
    Wassup?
  • Class names start with a capital letter.
  • Additional words in the name are capitalized.
  • Class names are never plural.
  • Class names are nouns, not verbs.
  • Methods are named for what the object knows how
    to do.
  • Field accessors and modifiers are named
    setField() and getField().

35
Making objects print nicely
  • When we print an object, the toString() method is
    called.
  • We can make it print something nicer than an
    internal object reference number.

36
Adding toString() to Person
Strings can be concatenated (combined) with
  • Now, Person instances can print themselves by
    name

37
Designing the Student class
  • By default, all classes inherit from (extend) the
    class Object.
  • Thats where toString() is that returns the funny
    number.
  • Well make Student a subclass of Person.
  • This is the UML diagram showing these
    relationships.

38
Student Definition1 A Student has an ID
This goes in a file named Student.java
39
Using our Student definition
40
But theres a problem
  • Students cant be created with names?
  • No-argument default constructor will always work.
  • If we want to access superclasss constructor,
    have to set up constructors that call super().

41
Student Definition 2
If youre going to call the superclass
constructor, call super() as the first statement
in the constructor.
42
Trying out Student definition 2
43
Creating a test method for Person
  • This method is always called public static void
    main(String args)

44
Exploring inheritance
  • A greet() method for Person

45
Overriding greet() in Student
  • Cant just say this.name because name is private.

46
Variables, Types and Classes
  • A variable of type superclass can hold any
    subclass, but not vice-versa.

47
Accessing subclass parts requires casting
48
Summarizing the terms so-far
  • Just about everything in Java is an object
  • Objects know specific things and can do specific
    things
  • Things they know are stored in variables (data)
  • Things they can do are grouped into methods
  • Think of methods as functions known only to
    instances of that class.
  • Objects are instances of a given class in Java.
  • All the instances know the same things and can do
    the same things.
  • Variables are specific to a given class, and can
    only refer to objects of that type.

49
Manipulating Pictures in Java
  • The class Picture has a constructor that takes a
    filename and returns a picture.
  • A picture can show()
  • FileChooser.pickAFile() returns a filename

50
(No Transcript)
51
Explaining whats going on
  • Every line ends with a semi-colon in Java.
  • (DrJava doesnt always require it.)
  • Picture is the name of a class in Java.
  • p is the variable that were declaring
  • gt Picture p
  • gt p new Picture("D/cs1316/MediaSources/Swan.jpg
    ")
  • gt p.show()

In Java programs, You can only use declared
variables! And you can only declare them once per
scope!
52
Explaining whats going on
  • new Picture() creates a new picture.
  • The pathname provided as an argument tells it
    which picture.
  • You can always use / and itll always work (on
    any platform)
  • p now refers to the new object (instance of
    class Picture)
  • gt Picture p
  • gt p new Picture("D/cs1316/MediaSources/Swan.jpg
    ")
  • gt p.show()

53
Explaining whats going on
  • Instances of the class Picture (objects created
    from the class Picture) know how to show
    themselves.
  • We access what the object knows and can do with
    the dot operator.
  • p.show() says Object that p refers to, would
    you please execute your show() method?
  • gt Picture p
  • gt p new Picture("D/cs1316/MediaSources/Swan.jpg
    ")
  • gt p.show()

54
Semicolons or not in DrJava Interactions Pane
  • No semi-colon says Evaluate this, and show me
    the result.
  • Semi-colon says Treat this like a line of code,
    just as if it were in the Code Pane.
  • gt p
  • Picture, filename D/cs1316/MediaSources/Swan.jpg
    height 360 width 480
  • gt p
  • gt

55
Pictures are made up of Pixels
  • Pictures are made up of picture elements called
    Pixels.
  • Pixel declares an array of Pixel objects.
  • Each Pixel has a red, green, and blue channel,
    which combine to show us a color for that Pixel.

56
Increasing red from DrJava Interaction pane
57
Defining a method in Picture to doubleRed()
58
Trying out our doubleRed() method
59
Testing doubleRed() on Big Ben
60
Adding the ability to flip() pictures (1 of 2)
  • /
  • Method to flip a picture
  • /
  • public Picture flip ()
  • // declare some local variables
  • Pixel currPixel null
  • Pixel targetPixel null
  • Picture target
  • new Picture(this.getWidth (),this.getHeight ())

61
Finishing flip()
  • / loop through the picture with the source x
    starting at 0
  • and the target x starting at the width minus
    one /
  • for (int srcX 0, trgX getWidth ()-1
  • srcX lt getWidth ()
  • srcX, trgX --)
  • for (int srcY 0, trgY 0
  • srcY lt getHeight ()
  • srcY, trgY )
  • // get the current pixel
  • currPixel this.getPixel(srcX ,srcY )
  • targetPixel target.getPixel(trgX ,trgY )
  • // copy the color of currPixel into target
  • targetPixel.setColor(currPixel.getColor ())
  • return target

62
Testing flip()
63
Testing flip()
64
Exploring sounds in Java
65
Explaining whats going on
  • gt Sound s new Sound(FileChooser.pickAFile())
  • gt s.play()
  • We can create an object as we declare the
    variable.
  • FileChooser is an object that knows how to
    pickAFile() which puts up a file picker and
    returns a string.
  • Instances of the class Sound know how to play,
    thus s.play()

66
What if we get it wrong?
67
An example with Music
  • gt import jm.util.
  • gt import jm.music.data.
  • gt Note n1
  • gt n1 new Note(60,0.5)
  • gt // Create an eighth note at C octave 4
  • JMusic pieces need to be imported first to use
    them.

68
Exploring Music in Java
  • gt import jm.util.
  • gt import jm.music.data.
  • gt Note n1
  • gt n1 new Note(60,0.5)
  • gt // Create an eighth note at C octave 4
  • Declare a Note variable.

69
An example with Music
  • gt import jm.util.
  • gt import jm.music.data.
  • gt Note n1
  • gt n1 new Note(60,0.5)
  • gt // Create an eighth note at C octave 4
  • Note instances have nothing to do with
    filenames.
  • To create a note, you need to know which note,
    and a duration

Starting a line with // creates a commentignored
by Java
70
MIDI notes
71
Making more notes
  • gt Note n2new Note(64,0.5)
  • gt View.notate(n1)
  • Error No 'notate' method in 'jm.util.View' with
    arguments (jm.music.data.Note)
  • gt Phrase phr new Phrase()
  • gt phr.addNote(n1)
  • gt phr.addNote(n2)
  • gt View.notate(phr)
  • -- Constructing MIDI file from'Untitled Score'...
    Playing with JavaSound ... Completed MIDI
    playback --------

72
Whats going on here?
gt Note n2new Note(64,0.5) gt View.notate(n1) Err
or No 'notate' method in 'jm.util.View' with
arguments (jm.music.data.Note)
  • Well make another Note (at E4, another eighth
    note)
  • There is an object named View that knows how to
    notate parts of music, but not an individual note.

73
Whats going on here?
gt Phrase phr new Phrase() gt phr.addNote(n1) gt
phr.addNote(n2) gt View.notate(phr) --
Constructing MIDI file from'Untitled Score'...
Playing with JavaSound ... Completed MIDI
playback --------
  • Well create a new Phrase instance and make a
    variable phr to refer to it. (phr has to be
    declared to be a Phrase.)
  • Phrase instances know how to addNote notes to
    them. These are methods that take an argumenta
    Note instance.
  • The View object does know how to notate an input
    Phrase instance. It generates this cool window
    where you see the notes and can play them (or
    save them as MIDI.)

74
Playing a different Phrase
  • gt Phrase nuphr new Phrase(0.0,JMC.FLUTE)
  • gt nuphr.addNote(n2)
  • gt nuphr.addNote(n1)
  • gt View.notate(nuphr)
  • We can specify when a phrase starts and with
    what instrument.
  • We can add notes (even the same notes!) in
    different orders

75
Modeling Music
  • The JMusic package is really modeling music.
  • Notes have tones and durations.
  • Musical Phrases are collections of notes.
  • We can play (and View) a musical phrase.
  • A phrase doesnt have to start when other phrases
    do, and a phrase can have its own instrument.

76
Objects know things and can do things
What instances of this class know What instances of this class can do
Note A musical pitch and a duration ltNothing weve seen yetgt
Phrase The notes in the phrase addNote(aNote)
77
The Organization of JMusic Objects
Score timeSignature, tempo,
Part Instrument
Part Instrument
Phrase startingTime
Phrase startingTime
Note (pitch,duration)
Note (pitch,duration)
Note (pitch,duration)
Note (pitch,duration)
Note (pitch,duration)
Write a Comment
User Comments (0)
About PowerShow.com