Transcript Slide 1

APCS-A: Java
November 8, 2005
week10
1
Java Packages
• All Java classes are grouped into libraries (or
packages)
 String is part of the java.lang package, which is preloaded when you are programming in Java
 We’ve already seen one other library, the java.util
library, where Scanner is
• Some of the other standard Java Libraries:




week10
java.applet
java.awt
java.io
java.lang
java.util
java.math
java.net
javax.swing
2
Using Packages
• Everything in java.lang is available for use
 So it’s as if somebody already did:
import java.lang.*;
• To use other packages, we need to import either
the specific class or the entire package (just like
we did for Scanner class)
 To import a class we use the whole package name:
import java.util.Scanner; import java.io.File;
 To import an entire library we use the asterisk:
import java.util.*; import java.io.*;
week10
3
Math Class
• Defined in the java.lang package
• All methods in the Math class are static methods (aka
class methods)
 This means that you do not need an object of the class to call the
methods - you invoke them directly through the name of the class
• Some useful methods:






week10
static double sqrt (double power)
static double pow (double num, double power)
static double random ()
static double cos (double num)
static double sin (double num)
static double tan (double num)
4
static
• Static Methods - invoked by class name, no
object needed
 Can be used when no object state is needed to do an
action
• Static Variables (also called Class Variables) are
shared among all instances of a class
 There is one copy of the variable for all objects in the
class
 This is different from an instance variable in which
each instance (object) has its own version of the
variable
week10
5
enum
• Enumerated type, lists all the possible values of
a variable of the type
 The values given are identifiers
• Examples:
enum Season {winter, spring, summer, fall}
enum Grade {A, B, C, D, F}
enum STA-grade {Aplus, A, Bplus, B, Cplus, C, Dplus,
D, F}
• Using an enum type:
STA-grade myGrade = STA-grade.Aplus;
Season time = Season.fall;
week10
6
More about Classes & Design
• Need to be consistent with our models and
•
design of classes. One way to do this is to use
UML (Unified Modeling Language) diagrams to
visualize programs
Use box to represent class
 Top box - Class name
 Middle box - instance variables
 Bottom box - methods
Song
length : int
artist : Artist
album : Album
play() : void
toString(): String
week10
7
Encapsulation
• The instance data of an object should only be
modified by that object
 Keep the data private
• Make other objects use getter (accessor) and
•
setter (mutator) methods to access and change
data
This guarding of data is called encapsulation
week10
public
private
variables
Violate
encapsulation
Enforce
encapsulation
methods
Provide services
to clients
Support other
methods in class
8
Figure 4.5
Wednesday
• Finishing up lecture from yesterday…
week10
9
Class Relationships
• Dependency (one class “uses” another)
 But how does a class gain access to another object?
• One class can instantiate (create) the other object
• One class can gain access to another by getting that object as
a parameter to a method
 The more classes depend on one another, the more
changes in one class can impact another (which can
be troublesome)
• Classes can depend upon objects of the same
class (ie one object of a class interacts with
another object of the same class)
week10
10
Class Relationships
• Composition (aggregation) - one object is
made up of other objects
 Can be described as a “has-a” relationship
 A special type of dependency
week10
11
Homework
• Write a class that will represent a student at STA or NCS.
This is a very simplistic model, but this student only
knows what form he or she is in, and can only do math
 The student should be assigned to a form when constructed
 Yesterday we talked about enums. They can be useful in many
situations, but here we will use it to define the range of legal
values for form assignment
 The student class should have a method called “doMath” that will
do the type of math appropriate for their grade level (defined
below)
• The function should use input and output as we have previously
done (input using Scanner)
• The method should make appropriate calls to static methods of the
Math class
week10
12
More Homework
• The following is the mapping of forms to the
math they can do









week10
C Form - parrot back the number you are given
B Form - give the IEEE remainder (std 754) of 2 nums
A Form - rounding a number
I Form - providing the absolute value of a number
II Form - exponentiation
III Form - Square roots
IV Form - Sin functions
V Form - provide the larger of two numbers
VI Form - Quadratic Formula
13
APCS-A: Java
Arrays
(related information in Chapter 7
of Lewis & Loftus)
November 11, 2005
week10
14
Grouping objects
• Fixed-sized collections
 When you know in advance how many items will be
stored in a collection (and that stays fixed for the life
of the collection)
 A fixed-sized collection is an array
• It’s kind of like a tray of cups – each cup can hold an object
or a primitive data type
• Note: the array itself is an object
• Flexible-sized collections
 When you don’t know in advance how many items
you will need to store
 Will go into more details about these in a few weeks
week10
15
Arrays
• An array is a group of
•
variables (called elements or
components) containing
values that all have the same
data type
To refer to a particular
element in an array, use the
array’s name and the position
number of the element in the
array
week10
int array called c
c[0]
-423
c[1]
3
c[2]
34
c[3]
54
c[4]
32
c[5]
2
c[6]
9
c[7]
4
c[8]
3453
16
Anatomy of an array
• Array names are the same as any other
•
•
•
•
variable name
An array with 9 elements (or variables)
First element has index zero (the zeroth
element)
ith element of array c is c[i -1]
Index must be a positive integer (or an
integer expression that can be promoted to
an int)
week10
int array called c
c[0]
-423
c[1]
3
c[2]
34
c[3]
54
c[4]
32
c[5]
2
c[6]
9
c[7]
4
c[8]
3453
17
Advantages to using arrays
• It is easy to access individual items in an
array (and it’s efficient)
• Arrays are able to store objects or primitive
type values (int, double, float, etc)
 (We’ll see later that the flexible-sized
collections can only store objects)
week10
18
Declaring and creating arrays
• Array objects occupy space in memory. All objects in
•
•
Java must be created with a keyword new
When you declare an array you must tell Java the type of
the array elements and the number of the elements that
will appear in the array
Example declaration for an integer array called
hourArray:
int hourArray[] = new int[24];
// declares and creates an array to hold 24 int elements
week10
19
An array
hourArray
:int[ ]
0
week10
1 2 3 4
5 6 7
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
20
How do we fill an array?
• All values are initially set to zero/null when we initialize
•
an array
One way to fill the array is to use an array initializer, a
comma-separated list of expression enclosed in braces:
when you declare it
int n[] = {10, 23, 34, 235, 234};
 The array length is automatically determined by the number of elements
in the initializer list
week10
21
Class Exercise
• Write code to declare and initialize an array
to hold the months of a year
• Write code to declare and initialize an array
to hold the number of days in each month
of the year
week10
22
How else do we fill an array?
• Any ideas about how else we could fill an array?
• A large number of the things we want to do with arrays involve
manipulating the entire array. Unfortunately, there are very few builtin operations that are defined to work on the contents of an entire
array. Instead, we must define those processes in terms of what they
require us to do to the individual elements of the array. This task is
then repeated once for each element of the array. Since the size of
the array is fixed once the array is allocated, it is a natural
application of a for-loop.
week10
23
How else do we fill an array?
• Arrays and for-loops go together like peanut butter and
jelly!
 For filling, for printing values, for checking values, etc
• We could use a for loop and access each array element
to set a value to it:
int myArray = new int[10];
for(int i =0; i < myArray.length; i++){
myArray[i] = 5 * i;
}
 Note: unlike the String class when we access the length of the array we
are not calling a method, rather we are accessing one of the array’s
instance variables
week10
24
Exercise
• Print out the names and lengths of each of the
months
week10
25
Mistakes
• It is not uncommon to make a programming mistake that
•
causes the bounds of a loop to be mis-defined and the
loop index variable to stray beyond the range of the array.
For example, what if in your for loop you wrote:
for(int i = 0; i <= array.length; i++){
System.out.println(array[i]);
}
week10
26
Lab/Homework
• Lab: LightsOut game - we will work on this
in class today and Monday
• Homework: Chess Design Project - Due
next Wednesday
• Note: Quizzes the next two Tuesdays.
week10
27