itm 352 simple arrays lecture #. 2/20/2003itm352 spring 2003 - © portarrays - 2 announcements r...

62
ITM 352 Simple Arrays Lecture #

Post on 21-Dec-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

ITM 352Simple Arrays

Lecture #

Page 2: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 2

Announcements Grades for assignment #1 posted on web site

Use your class ID #

Exam questions posted on web site Study early!

For those who feel they need extra help, come to the extra lab session Friday anytime 12-3pm

Page 3: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 3

Today Informal Survey Review:

Methods method definition methods and ivars parameters, parameter passing constructors

Some example programs: “mini” robot development

Simple Arrays

Page 4: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 4

Informal SurveyWhere are you at now?

Understand basic OO concepts of objects, classes, variables

Can successfully modify OO code(if you are still here then attend Friday extra classand TA labs)

Can design and write simple OO apps(around 3 classes or less)

Can analysis, design complex OO apps(more than 8 classes, GUI, multiple entry,..)

Page 5: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 5

Informal Survey: actionsDo you feel you have [too little, too

much, just enough] opportunities for programming practice and examples?

Page 6: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 6

Informal SurveyOverall are you [happy, unhappy] with this

class as it stands now?

Page 7: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 7

Review

Page 8: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 8

Objects and Methods

Page 9: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 9

Method calls Calling a method is a way of executing a bunch of

Java statements that appear elsewhere. Those statements appear in a method definition, which may be written by you or supplied by the system.

To invoke a method, you do not have to know what statements it contains, but you do have to know what they do, and you have to know the method name.

Methods carry out an objects behaviors

Page 10: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 10

Object messaging: using methods Behaviors are the result of object interaction

through messaging

myRobot world

caller receiver

robotLocation()

Page 11: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 11

Object messaging itself It is very common (and elegant when appropriate)

for an object to message itself

The special keyword this always refers to the current object any method call that does not begin with a reference implicity has

a this in from of it

myRobot

caller

receiver

this.selfTest()

Page 12: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 12

Method calls (cont.) Two flavors of methods: class methods and

instance methods. SavitchIn.readLine() is a class method.

Class methods are always called using the name of the class (SavitchIn), a period, and then the name of the method (readLine).

world.robotLocation()is an instance method. Instance methods are always called using a reference to an object (i.e. an instance of a Class)

Page 13: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 13

Method ParametersMethods can accept any number of

arguments of any data type each argument must be specified in the method

definition

setRobotDirection(int degrees, Engine engine, Robot robot)

Question: what might be a problem with the above?

Page 14: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 14

Parameter Passing Arguments are passed from the caller to the

receiver when the method is called

movingRobotTest myEngine

caller receiver

myEngine.moveInDirection(270);

Page 15: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 15

Complex messaging Calling a method may invoke the calling of other

methods indirectly

movingRobotTest myEngine

caller

receiver_1

myEngine.moveInDirection(270);

world

receiver_3

this.setDirection(270);

receiver_2

world.setDirection(270,this);

Page 16: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 16

Return values from methods

Most methods return a value. SavitchIn.ReadLine() returns a String world.robotLocation() returns a Point

Such methods can appear in expressions. System.out.print(“You entered: “+ SavitchIn.ReadLine());

Documentation says what the argument types and return value are.

Page 17: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 17

Return values

Return types are declared in the method definition indicate the data type of value to be returned special void keyword denotes no return value

static int readLineInt() { … } static String readLine() { … } public void moveInDirection() { … }

actual return values are passed via the return keyword inside the method implementation

Page 18: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 18

Return Values Values are passed back from the receiver to the

caller when the method completes using the return keyword

myRobotTest myRobot

caller receiver

System.out.println(myRobot.getName());

“HAL200”

String getName(){ return “HAL2000;}getName()

Page 19: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 19

Accessibility (scope) of methods

The accessibility of a method is defined in its definition before its return type public static int readLineInt() { … } private void setBankBalance(int amount) { … }

Page 20: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 20

Constructor methods

To create an object (instance of a class), use the expression

new classname () ;Remember: variables must be initialized!

Variables with object types are no exception.Initialization is usually done within a special

method called a constructor

Page 21: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 21

Multiple ConstructorsConstructors can take arguments, but never

return values (they return references) public class Robot {String name;Robot() {} // the default constructorRobot(String aName) {// use passed parameter to initialize name

name = aName;}

} This constructor is different than Robot() , both can

be defined and used when appropriate.

Page 22: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 22

Object References When you do

new <classname>() ;

the constructor <classname>() is called in the class <classname> and a reference is returned

This reference usually is assigned to a variable of type <classname> Ex. Robot myRobot = new Robot();

The keyword null represents “no reference” When you declare an object type (i.e. a class), the default

initialization is to null

Page 23: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 23

Reference Variables Object references can be used just like any value (int, float,

etc.) except you can not use arithmetic or most logical operators on them (unlike C++) WRONG:

myRobot++; myRobot + anotherRobot; myRobot > anotherRobot;

OK: myRobot = anotherRobot // assign ref. value myRobot = = anotherRobot // test “is same ref?”

Object references can be uses as arguments for parameter passing Robot getRobot(); return myRobot;

Page 24: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 24

Basic Variable Scope

Variables are containers for values that are local to a method

public class CircleArea {

public static void main (String[] args) {

final float MY_PI = 3.1415; double radius = 4.12333422;

System.out.print("area = "); System.out.println(MY_PI*radius*radius); } }

Only “seen” in main block

Page 25: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 25

Class Variables

A class can introduce variables (or symbolic constants) that can be referred to by classname . Variablename Do not need an instance of the Class to use Examples: Math.PI, System.out

public class CircleArea {

public static void main (String[] args) {

final float MY_PI = (float) Math.PI double radius = 4.12333422;

System.out.print("area = "); System.out.println(MY_PI*radius*radius); } }

“seen” anywhereclass isavailable

Page 26: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 26

Instance variables and class variables An object can contain variables referred to by

object . Variablename or anywhere inside the class definition block (available to all methods)

public class CircleArea {

double radius = 4.12333422;

public static void main (String[] args) {

System.out.print("area = "); System.out.println(Math.PI*radius*radius); } } ---------- in another object that has “aCircleArea” as a reference ----------System.out.print(”the radius is ”, aCircleArea.radius);

“seen” in classblock or outside throughreference

Page 27: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 27

Summary

Objects have: Instance methods: expression . methodname (arg’s) Instance variables: expression . variablename

Variables declared inside main (or other methods) are called local variables. These are different from class variables and instance variables, and are referred to simply by their names.

Page 28: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 28

And now an extended example!

Page 29: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 29

“mini” Robot ExampleA robot has attributes:

name represent using a string

environment represent using a RobotEnvironment object

And behaviors: check status

battery, damage level use parts

only need to add parts, get parts

Page 30: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 30

Robot Robot

Environmentworld

Robot

Test

myRobot theWorld

Page 31: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 31

The Robotpublic class Robot {/* This is the robot representation */

public String name; // the name ivarpublic RobotEnvironment world; // the world attr ivar

Robot(RobotEnvironment theEnv) { // constructor for a Robotthis.world = theEnv;usePart(new RobotPart(“lazer”);

}

public String checkStatus() {return world.checkRobotStatus(this);

}

public void usePart(RobotPart aPart) {world.addPartForRobot(this, aPart)

}}

Implies RobotEnvironment will have these methods

Implies another class called RobotPart

Page 32: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 32

“mini” Robot Test Class

public class RobotTest {

public static void main(String[] args) {Robot theRobot = new Robot( new RobotEnvironment() );System.out.println(“Status:”+ theRobot.checkStatus());

}}

Define methods that implement behaviors

Page 33: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 33

End of Review

Page 34: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 34

Simple Arrays

Page 35: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 35

Arrays

CollectionsArray basics

Declaration, allocation, and initialization Subscripting

Processing arrays by iteration and recursionReading and writing arrays

Page 36: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 36

CollectionsA collection is a value that contains other

values. Arrays are a kind of collection. We have already seen a kind of collection, strings. These in turn could be used to create another kind of collection, lists (to be discussed later). Both are ordered collections. Strings: collections of characters. Note operation charAt (get nth character, counting from zero).

Page 37: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 37

Arrays

Another kind of ordered collection.Special features:

Built-in to language, has special syntax. Elements are variables, so can be changed as

well as referenced. Collection has fixed size (once created) Access to nth element takes constant time.

Page 38: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 38

Arrays (cont.)

Definition An array is a fixed-size collection of variables, all of the same type.

an arrayof ints 17 4 9 20 47

an arrayof Strings

“Don’t” “forget” “to vote” “tomorrow”

Page 39: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 39

Declaring and allocating arrays

Declaring: Each array has a name. Declare arrays like this:

N.B. As with any other variable declaration, this creates the variable, but puts nothing in it:

int[] grades;String[] message;Time[] clocks;

grades message clocks

Page 40: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 40

Declaring and allocating arrays (cont.)

To create the actual collection of variables, use new:

Array is allocated in a heap and the variable gets reference value to it (just like an object):grades = new int[100];message = new String[4];clocks = new Time[8];

heapallocation

Page 41: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 41

Declaring and allocating arrays (cont.)

As usual, allocation can be done in declaration: int[] grades = new int[100];

Never forget to allocate an array (very common error).

grades message clocks

Page 42: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 42

Initializing arrays

Note that allocating an array initializes the array variable itself, but does not initialize the variables contained in the array.

Variables in the array must be initialized before use, like any other variables.

Page 43: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 43

Initializing arrays (cont.) One method: initialization list.

This allocates the array as a 3-element array and initializes its elements. Any type of array can be initialized with this notation, e.g.

We’ll see a more general method of initialization shortly.

double[] angles = {3.5, 9.7, 15.01};

Time[] clocks = {new Time(3,30), new Time(4,30)};

Page 44: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 44

Subscripting Principal feature of arrays: ability to access each

component easily. Use notation

to access elements of an array. If the integer-expression has value n, this returns the n th elements in array-name, counting from zero.

Note that the expression denotes a variable, so can appear on the left-hand side of assignment statements, as well as in expressions.

array-name[integer-expression]

Page 45: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 45

Subscripting (cont.)

Examples: Suppose we have declarations as above:

Then these statements are legal:

int[] grades = new int[100];String[] message = new String[4];Time[] clocks = new Time[8];

grades[0] = 75;message[0] = “Don’t”;int i = 2;clocks[i-1] = new Time(3,30);

Page 46: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 46

Subscripting (cont.)

But these statements are illegal:// subscripts range from zero to// size of array - 1grades[-1] = 90; // illegalgrades[100] = 75; // illegal// must assign correct type of value// to array elementmessage[0] = grades[0]; // illegal// subscripts are always int’sdouble i = 2;clocks[i-1] = new Time(3,30); // illegal

Page 47: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 47

Subscript out of Range Error

Using a subscript larger than length-1 causes a run time (not a compiler) error an ArrayOutOfBoundsException is

thrownyou do not need to catch it or declare it in a

throws-clauseyou need to fix the problem and recompile

your code

Page 48: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 48

Array initialization (revisited) Assignment to array elements provides a more general method of initializing arrays.

Using assignment in loops also makes it easy to initialize large arrays (examples later).

String[] message = new String[4];message[0] = “Don’t”;message[1] = “forget”;message[2] = “to vote”;message[3] = “tomorrow”;

Page 49: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 49

Finding the length of an array Size of array A is value of instance variable A.length. Useful when an array is passed as an argument to a method:

Note: subscripts range from 0 to A.length-1

void dosomethingtoarray ( double[] Xs ) { . . .} How big is Xs? Can’t tell from

declaration. Use Xs.length.

Page 50: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 50

Summary Array variable must be declared, then it must be

initialized by allocating an array, then the array must be initialized.

The following typical sequences have the same effect:

String[] holidays = {“Labor Day”, “Thanksgiving”, “Christmas”};

declareallocate and initialize

Page 51: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 51

Summary (cont.)

String[] holidays = new String[3];holidays[0] = “Labor Day”;holidays[1] = “Thanksgiving”;holidays[2] = “Christmas”;

declare

allocateinitialize

String[] holidays;holidays = new String[3];holidays[0] = “Labor Day”;holidays[1] = “Thanksgiving”;holidays[2] = “Christmas”;

declare

allocate

initialize

Page 52: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 52

Three Ways to Use [ ] (Brackets)with an Array Name

1. To create a type name, e.g. int[] pressure; creates a name with the type "int array" note that the types int and int array are different it is the type of the name, not the type of the data

2. To create a new array, e.g. pressure = new int[100];

3. To name a specific element in the array- also called an indexed variable, e.g.pressure[3] = SavitchIn.readLineInt();System.out.println("You entered" + pressure[3]);

Page 53: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 53

Some Array Terminology

temperature[n + 2]

temperature[n + 2]

temperature[n + 2]

temperature[n + 2] = 32;

Array name

Index - also called a subscript - must be an int, - or an expression that evaluates to an int

Indexed variable - also called an element or subscripted variable

Note that "element" may refer to either a single indexed variable in the array or the

value of a single indexed variable.

Value of the indexed variable- also called an element of the array

Page 54: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 54

Why arrays? Lists can be “subscripted” using nth method. Plus,

could define a method assign that would allow us to change elements in a list. So why do we need arrays?

Efficiency: access to array elements takes constant time, whereas nth(L,i) takes time proportional to i. The difference in efficiency has a deep effect on the design of algorithms using these data structures.

Page 55: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 55

Simple array processingArrays can be processed using iteration or

recursion.Standard array-processing loop:

Historically, arrays most common kind of collection; iteration most common method of processing them.

for (i=0; i<A.length; i++) { // process array element A[i]}

Page 56: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 56

Simple array processing (cont.)When processing arrays recursively, need to

pass a smaller array in the recursive call. It is inefficient to construct new arrays, so instead we will pass an additional integer (or integers) representing a part of the array.

void processArray (double[] A, int i) { if (i != A.length) { // process A[i], then make recursive call // processArray(A, i+1) }}

Page 57: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 57

Printing arraysPrint an integer array A:Iteration:

Recursion (call: printArray(A,0)):

for (i=0; i<A.length; i++) System.out.println(A[i]);

void printArray (int A[], int i) { if (i != A.length) { System.out.println(A[i]); printArray(A, i+1); }}

Page 58: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 58

Reading arraysRead 10 elements into array A:Iteration:

Recursion (call: printArray(A,0)):

for (i=0; i<10; i++) A[i] = Keyboard.readInt();

void readArray (int A[], int i) { if (i < 10) { A[i] = Keyboard.readInt(); readArray(A, i+1); }}

Page 59: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 59

Reading up to eofDisadvantage of arrays: they cannot grow

once allocated.How can you read all the values into an

array without knowing beforehand how many there are? Make an array large enough to hold as many inputs as you’re likely to get. Suppose A is very large:

int[] A = new int[1000];

Page 60: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 60

Reading up to eof (cont.)Read integers up to eof:Iteration:

i = 0;while (true) { A[i] = Keyboard.readInt(); if (Keyboard.eof()) break; i = i+1;}// i = number of integers read// N.B. i != A.length

Page 61: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 61

Reading up to eof (cont.)

Recursion:

int readArray (int[] A, int i) { A[i] = Keyboard.readInt(); if (Keyboard.eof()) return i; readArray(A, i+1);}

// Call: readArray(A, 0). Return value// is number of integers read.

Page 62: ITM 352 Simple Arrays Lecture #. 2/20/2003ITM352 Spring 2003 - © PortArrays - 2 Announcements r Grades for assignment #1 posted on web site m Use your

2/20/2003 ITM352 Spring 2003 - © Port Arrays - 62

Another Mystery Resolved!!

public static void main(String[] args) {

for (int i=0; i<args.length; i++)

System.out.println(“input argument “ + i + ”=“ + args[i]);

}

Java MyClass a b c d e f g

Will print out “a b c d e f g” each of which are elements ofthe array String[] args