comp 10 introduction to programming mr. joshua stough october 29, 2007

36
COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Post on 15-Jan-2016

218 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

COMP 10Introduction to Programming

Mr. Joshua StoughOctober 29, 2007

Page 2: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Debugging Tips

• Pay attention to detail!– Java is case-sensitive– difference between () and [] and {}

• Double-check loop conditions• Work through errors one at a time• Add println statements to show values

of variables before/after errors occur• Take a break!

Page 3: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Spot the Bug

public class Errors{ public static void main (String[] args) {

int[] numbers = {8, 4, 5, 7};

for (int i=0; i<=numbers.length; i++) { System.out.println (numbers(i));}

}} Errors.java:8: cannot resolve symbol

symbol: method numbers (int)location: class Errors

System.out.println (numbers(i)); ^

1 error

Page 4: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Spot the Bug

public class Errors{ public static void main (String[] args) {

int[] numbers = {8, 4, 5, 7};

for (int i=0; i<=numbers.length; i++) { System.out.println (numbers[i]);}

}}

8457Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4at Errors.main(Errors.java:8)

Page 5: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

ReviewVisibility Modifiers• public visibility

– can be accessed from anywhere

• private visibility – can only be accessed

from inside the class (inside the same Java source file)

public class Rectangle{

private int length;private int width;

}

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

...

Page 6: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

ReviewVisibility Modifiers• Usually declare data members with private visibility

• Declare methods that clients (other classes) are supposed to call with public visibility– service methods

• Declare methods that only other methods in the class are supposed to call with private visibility– support methods

Page 7: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Review - Constructor

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;}

All formal parametersare local to the method.

Page 8: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

r2500

2500

2 3

ReviewObjects• Create an object:

Rectangle r;r = new Rectangle(2, 3);ORRectangle r = new Rectangle(2, 3);

• Use the object and the dot operator to access methods:r.setLength(5);r.setWidth(10);

r

2 3

25002500

5 10

Page 9: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

ReviewAccessing Static Members

public class Card{

public static final int ACE = 14;

public class BlackjackGame{

public static int calcPoints (Card card)

Card.ACE

BlackjackGame.calcPoints

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

ReviewCalling Methods

• static methods– classname.methodname

• non-static methods– create an object– objectname.methodname

Page 11: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Reviewthis

public class Rectangle{

private int length;private int width;

public Rectangle (int length, int width){

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

}

Page 12: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

ReviewPassing Objects as Parameters

public class BlackjackGame{ public static int calcPoints(Card c) {

}}

Card card1 = new Card (2, Card.HEARTS);

card1 face 2

suit 0

c

int points = BlackjackGame.calcPoints(card1);

2

points

Page 13: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Array Bounds

• Arrays have finite size

• If you access an element outside of the array, you’ll get an ArrayIndexOutOfBounds Exception

Example:Int[] grades = {99, 98, 95, 96};System.out.println (grades[4]);

0 1 2 3

Page 14: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

int arraySize;

System.out.print ("Enter the size of the array:"); arraySize = Integer.parseInt(keyboard.readLine());

int[] list = new int[arraySize];

Specify Array Size During Program Execution

Example0 1 2 3

(Assume that keyboard has already been declared and instantiated.)

Page 15: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Example

for (int ind = 0; ind < sale.length; ind++) { sale[ind] = 10.00;}

Initialize Array to Specific Value (10.00)

(Assume that sale has already been declared and instantiated.)

0 1 2 3

Page 16: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Example

for (int ind = 0; ind < sale.length; ind++) { sale[ind] = Double.parseDouble(keyboard.readLine());}

(Assume that sale has already been declared and instantiated, and that keyboard has already been declared and instantiated.)

Read Data into Array

0 1 2 3

Page 17: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Example

for (int ind = 0; ind < sale.length; ind++) { System.out.print(sale[ind] + " ");}

Print Array

(Assume that sale has already been declared and instantiated.)

0 1 2 3

Page 18: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Example

sum = 0;for(int ind = 0; ind < sale.length; ind++) { sum = sum + sale[ind];}

if(sale.length != 0) average = sum / sale.length;else average = 0.0;

Find Sum and Average of Array

(Assume that sale has already been declared and instantiated,and that sum and average have already been declared.)

0 1 2 3

Page 19: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Example

maxIndex = 0;for (int ind = 1; ind < sale.length; ind++) { if (sale[maxIndex] < sale[ind]) { maxIndex = ind;

}}largestSale = sale[maxIndex];

Determining Largest Element in Array(Assume that sale has already been declared and instantiated,and that maxIndex and largestSale have already been declared.)

0 1 2 3 4 5 6 7

12.50 8.35 19.60 25.00 14.00 39.43 35.9098.23

0 1 2 3

Page 20: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Parallel Arrays

Arrays are parallel if corresponding components hold related information

String[] studentName;double[] studentGPA;

For example, studentName and studentGPA are parallel if studentGPA[3] is the GPA of the student with studentName[3].

0 1 2 3

Page 21: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

In-Class Exercises

1. Declare an array of integers called numbersHint: type[] name;

2. Declare and instantiate an array of 26 characters called alphabetHint: type[] name = new type[size];

int[] numbers;

char[] alphabet = new char[26];

0 1 2 3

Page 22: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

In-Class Exercises

3. Declare an array of 5 characters called grades and initialize it with the letters: A, B, C, D, FHint: type[] name = {initialization list};

4. Write a loop to print the contents of an array named zipCodesHint: to access array element name[index]

char[] grades = {'A', 'B', 'C', 'D', 'F'};

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

}

0 1 2 3

Page 23: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

In-Class Exercises

5. Write a loop to change all the values of the integer array numbers to index + 1

for (int i=0; i<numbers.length; i++) { numbers[i] = i+1;

}

0 1 2 3

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

ArraysSummary

• Why use them?– maintain a list of related items

• How use them?– first declare a variable to reference the

array– when your program knows how many

elements, it can then instantiate (create), initialize, and access the array

– design code to index the array only within the array bounds

0 1 2 3

Page 25: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

ReviewArrays• Declaration

int[] counts;

• Instantiationcounts = new int[50];

• Initialization / Accessfor (int i=0; i<counts.length; i++) {counts[i] = 0;

}

• Initializer List– declaration, instantiation, and initializationdouble[] grades = {98.7, 72.4, 87.5};int[] numbers = {num, num+1, num+2, num+3};

can use variables andexpressions as initial values

0 1 2 3

Page 26: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Arrays and Assignment

counter

01

23

4

int[] counter = new int[5];

int[] temp;

temp

temp = counter;

doesn't make a copy of the array!

temp == counter is true sincethe reference variables containthe same address

Page 27: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Copying Arrayscounter

01

23

4

int[] counter = {1, 2, 3, 4, 5};

1

23

4

5

int[] temp = new int[counter.length];

01

23

4

temp

for (int i=0; i<counter.length; i++) {temp[i] = counter[i];

}

1

23

4

5

i

012345

Page 28: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

References and Assignment

counter

01

23

4

1

23

4

5

01

23

4

temp

temp = counter;

1

23

4

5

Remember that arrays use reference variables just like objects.

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

References and nullcounter

01

23

4

1

23

4

5

01

23

4

temp

temp = null;

1

23

4

5

Remember that arrays use reference variables just like objects.

null is a reserved wordthat means "empty"

Page 30: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Arrays as Parameters

• Entire array can be passed as a parameter– method can change elements of the

array permanently– since we're passing a reference

• Elements of an array can be passed as parameters, too– normal rules apply…

Page 31: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

public class Tester{ public static void swap (int[] scores, int x, int y) {

int temp = scores[x];scores[x] = scores[y];scores[y] = temp;

}

public static void main (String[] args) {

int[] grades = new int[4];

for (int i=0; i<grades.length; i++) {grades[i] = i*10;

}

swap (grades, 2, 3); }

}

grades[2]: 20grades[3]: 30grades[2]: 30grades[3]: 20

scores[2]: 20scores[3]: 30temp : 20

scores[2]: 30scores[3]: 30temp : 20

scores[2]: 30scores[3]: 20temp : 20

Page 32: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Arrays as Parameters

public static void swap (int[] scores, int x, int y)

swap (grades, 2, 3);

alias

01

23

grades

0

1020

30

scores x 2

y 3

temp

int temp = scores[x];scores[x] = scores[y];scores[y] = temp;

20

20

30

Page 33: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 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 34: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Yahtzee

• Game of Yahtzee requires 5 dice

• Die– member variable: – methods:

int face

void roll()int getFace()

Die()

Page 35: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

Instantiating Array Objects

Die[] dice = new Die[5];

for (int i=0; i<dice.length; i++) {dice[i] = new Die();

}

01

23

4

dice

face

face

.

.

.

each element in the arrayis a reference variable

Page 36: COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007

dice[0] == dice[1]

Comparing Objects== vs. equals method

dice[0].equals(dice[1])

• If equals method for the class is undefined• are the variables aliases? (i.e., do the variables contain the same address?)

• If equals method for the class is defined• depends on the implementation of equals

are the variables aliases? (i.e., do the variables contain the same address?)