comp 110 introduction to programming mr. joshua stough october 24, 2007

30
COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Post on 21-Dec-2015

221 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

COMP 110Introduction to Programming

Mr. Joshua StoughOctober 24, 2007

Page 2: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Today

• Review• Reserved word this

• Arrays

Page 3: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Announcements

• HW6

Page 4: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

ReviewScope

public class Rectangle{

// variables declared here are class-level// available in all methods in Rectangle class

public int computeArea() {

// variables declared here are method-level// only available in computeArea()

}

public void print() {

// variables declared here are method-level// only available in print()

}

}

Page 5: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

The Reference this

• Reserved word

• Refers to instance variables and methods of a class

• Allows you to distinguish between member variables and local variables with the same name

Page 6: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Rectangle.java

public class Rectangle{

private int length;private int width;

public Rectangle (int length, int width){

this.length = length; this.width = width;

}

Page 7: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Reference Variables as Parameters

If a formal parameter is a reference variable:– copies value of corresponding actual

parameter– value of actual parameter is address

of object where actual data is stored– both formal and actual parameter

refer to same object

Page 8: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

ReviewOverloading Methods• Overloading - the process of using the same

method name for multiple methods

• The signature of each overloaded method must be unique– number of parameters– type of the parameters– not the return type of the method, though

• The compiler determines which version of the method is being invoked by analyzing the parameters

Page 9: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Review

public Rectangle (int l, int w){ length = l; width = w;}

public class Rectangle{

private int length;private int width;

Rectangle r2 = new Rectangle (5, 10);

public Rectangle (){ length = 0; width = 0;}

Page 10: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Review

• A method should be relatively small– it should be able to be understood as a

single entity– its name should fully describe its function

• A potentially large method should be decomposed into several smaller methods as needed for clarity

• A service method of an object may call one or more support methods to accomplish its goal

Page 11: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Thought Exercise

Write a method for the Rectangle class called printBox that will print the rectangle as a box made of %

example: length = 3, width = 5

%%%%%% %%%%%%

Page 12: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

public void printBox (){

for (int i = 1; i <= width; i++)System.out.print("%");

System.out.println( );

for (int i = 1; i <= length - 2; i++) { System.out.print("%");

for (int j = 1; j <= width - 2; j++) System.out.print(" ");

System.out.println("%");}

for (int i = 1; i <= width; i++) System.out.print("%"); System.out.println( );}

%%%%%%%%% %%%%%%%%%

length = 3, width = 8

Page 13: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

The toString Method

• Special method in Java classes• Produces a String object based on the

current object, suitable for printing• Mapped to the '+' operator• Also called when the object is a

parameter in a print() or println() method

• There is a default toString method, but it's better if we write our own

Page 14: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Rectangle.java

public String toString(){

String result = "";result += "length: " + length + "\n";result += "width: " + width;return (result);

}Rectangle r = new Rectangle (2,3);System.out.println (r);

length: 2width: 3

Page 15: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

The Modifier static

• In the method heading, specifies that the method can be invoked by using the name of the class– no object has to be created in order to use the

method– can't call a non-static method from a static

method– can't access non-static variables from a static

method

• If used to declare data member, data member invoked by using the class name– no object has to be created in order to use the

variables

Page 16: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

static Variables

• Shared among all objects of the class• Memory created for static variables

when class is loaded– memory created for instance variables (non-

static) when an object is instantiated (using new)

• If one object changes the value of the static variable, it is changed for all objects of that class

Page 17: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Illustrate Classpublic class Illustrate{ private int x; public static int y; private static int count;

public Illustrate() {

x = 0; }

public Illustrate (int a) {

x = a; }

public static void incrementCount() {

count++; }}

Illustrate obj1 = new Illustrate(3);

x 3

x 5

0y

count 0

obj1

obj2

Illustrate.incrementCount();

1

1

Illustrate obj2 = new Illustrate(5);

Illustrate.y++;

Page 18: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Arrays

• An array is a list of values that can be represented by one variable

• Members of an array must all have the same data type

• Each value is stored at a specific, numbered position in the array– the number corresponding to each position

is called an index or subscript

• All arrays have a length– number of elements the array can hold

0 1 2 3

Page 19: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Declaring Arrays

type[] name;

The array (element) data type Empty square brackets

The array (variable) name

Creates a reference variable called name that can point to an array of type elements.

0 1 2 3

Page 20: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Declaring ArraysExamples

// array of characterschar[] characterSet;

// array of counters (integers)int[] counter;

// array of grades (doubles)double[] grade;

counter

characterSet

grade

0 1 2 3

Page 21: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Instantiating Arrays

You must instantiate (create) arrays– the size of an array is typically not

known before run time

name = new type[size];

The array (element) data type

The new operatorThe array(variable) name

The assignment operator

The number of elements

0 1 2 3

Page 22: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Instantiating ArraysExamples

// instantiate an array of counterscounter = new int[5];

// instantiate the array of gradesnumStudents = 10;grade = new double[numStudents];

counter

01

23

4

0 <= index < size

0 1 2 3

Page 23: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Declaration and Instantiation

type[] name = new type[size];

Declaration Instantiation

0 1 2 3

Page 24: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Arrays of Objects

• Can use arrays to manipulate objects• Create array of objects

• Must instantiate each object in array

classname[] array = new classname[size];

for(int j=0; j <array.length; j++) {array[j] = new classname();

}

Page 25: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Example

int[] num = new int[5];

0 1 2 3

Page 26: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Array AccessExamples

averageScore = (score[0]+score[1]+score[2])/3;

numStudents = 3;totalScore = 0;for (int i = 0; i < numStudents; i++) { totalScore += score[i];}averageScore = totalScore/numStudents;

double score[] = new double[3];

score[0] = 98.3;score[1] = 57.8;score[2] = 93.4;

often use loops for access

0 1 2 3

Page 27: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Array Length

Arrays have length– an internal variable called length– number of elements in array– access the length variable using the

“dot’ notation (arrayname.length)

// loop through the array of test scoressumOfScores = 0;for (int i=0; i<scores.length; i++) { sumOfScores += scores[i];}

0 1 2 3

Page 28: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

int counter[] = {0, 0, 0, 0, 0};char[] characterSet = {‘a’,’b’,’c’}; // etc.

Initializing Arrays

• Array elements are variables too!– if you don’t initialize, the contents are

undefined

• When and how?– if you don’t yet know the size

• initialize at run time, typically with a loop

– if you know how many elements• perhaps use an initializer list

0 1 2 3

Page 29: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

• Lists the initial value for the elements of an array

• Items are separated by commas and the list is in braces {}

• The size of the array is determined by the number of items in the list

int[] scores = {87, 98, 45};• Can only be used in the same statement

as declaring the arrayNOT int[] scores;

scores = {87, 98, 45};

Initializer Lists0 1 2 3

Page 30: COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007

Next Time in COMP 110

• Arrays

• Reading Assignment: Ch 9