week101 apcs-a: java november 8, 2005. week102 java packages all java classes are grouped into...

27
week10 1 APCS-A: Java November 8, 2005

Upload: kristina-stone

Post on 28-Dec-2015

231 views

Category:

Documents


0 download

TRANSCRIPT

week10 1

APCS-A: Java

November 8, 2005

week10 2

Java Packages

• All Java classes are grouped into libraries (or packages) String is part of the java.lang package, which is pre-

loaded 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: java.applet java.util java.awt java.math java.io java.net java.lang javax.swing

week10 3

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 4

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: 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)

week10 5

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 6

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 7

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 : intartist : Artist

album : Album

play() : voidtoString(): String

week10 8

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

Violate encapsulation

Provide services to clients

Support other methods in class

Enforceencapsulation

public private

variables

methodsFigure 4.5

week10 9

Wednesday

• Finishing up lecture from yesterday…

week10 10

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 11

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 12

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 13

More Homework

• The following is the mapping of forms to the math they can do 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

week10 14

APCS-A: Java

Arrays

(related information in Chapter 7 of Lewis & Loftus)

November 11, 2005

week10 15

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 16

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

54

32

2

9

4

3453

34

3

-423

int array called c

c[0]

c[3]

c[4]

c[5]

c[6]

c[7]

c[8]

c[1]

c[2]

week10 17

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)

54

32

2

9

4

3453

34

3

-423

int array called c

c[0]

c[3]

c[4]

c[5]

c[6]

c[7]

c[8]

c[1]

c[2]

week10 18

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 19

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 20

An array

hourArray

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

:int[ ]

week10 21

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 22

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 23

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 built-in 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 24

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 25

Exercise

• Print out the names and lengths of each of the months

week10 26

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 27

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.