arrays, loops weeks 4-6 (change from syllabus for week 6) chapter 4

36
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

Post on 21-Dec-2015

218 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

Arrays, Loopsweeks 4-6

(change from syllabus for week 6)

Chapter 4

Page 2: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

• Each variable only holds one item

• if > 1 item wanted, need an array

• array that holds a word

• arrays hold elements all of the same type

char[ ] word = new char[4];

• holds 4 elements of type char

Arrays

0 1 32

word

Page 3: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

char[ ] word = new char[4];

two parts to an array:

index -- integer

element – type inside array

'h' 'e'

0 1 32

'h'

0 1 32

word[1] = 'e';

'h' 'e' 'o''r'

0 1 32

'h' 'e' 'o'

0 1 32

word[3] = 'o';

word[2] = 'r';

word[0] = 'h';

Page 4: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

• Can use variables for index OR elementsint i=3; char new = 'd';word[i] = new;

• can find lengthword.length // is 4• largest index is always length – 1• word[4] is RUN time error

Array manipulation

'h' 'e' 'o''r'

0 1 32

'h' 'e' 'd''r'

0 1 32

Page 5: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

arrays and new

char[ ] word;

• creates word that is of type char array that points to nothing

word = new word[4];

• creates array of 4 elements initialized to \u0000 (Java always initializes primitives to 0)

Page 6: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

Myarray example

public class Myarray

{

private static Circle[] circles;

private static double[] area;

// other stuff in the class

}

Page 7: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

Myarray gets elements allocated

• Create an object

circles = new Circle[4];

area = new double[4];

Page 8: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

createcircles()

• createcircles()

circles[0] = new Circle();

Page 9: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

array creation summary

• char[ ] word;creates a space named word that contains null• word = new char [4];allocates 4 chars, initialized, word points to them• classes: Circle[ ] mycircles;same as word • mycircles = new Circle[4];allocates 4 spaces that contain null• mycircles[0] = new Circle( );creates an actual circle

Page 10: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

Repetition in arrays

• arrays often do the same thing

(e.g., for each Circle in array, create a Circle)

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

circles[i] = new Circle( );

memorize this line

Page 11: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

Do: On the board

• Write code to declare a 4 character word array, then write a loop to initialize chars in word to be 'A'

• Write code to declare a 4 character array, then write a loop to initalize chars in word to be ABCD (do this in a loop). Hint: use a separate variable for the element value (start with 'A')

• Declare an int array with 10 integers and write a loop to put the value of the index into the element (e.g., intarray[3] should have the value 3)

Page 12: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

Loops

Notes adapted from Dr. Flores

Page 13: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

• It repeats a set of statements while a condition is true.

while (condition) { execute these statements;}

“while” structures

Page 14: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

“while” structures• It repeats a set of statements while a condition is true.

while ( condition ) { execute these statements;}

22

11

33The dynamics of “while”

Evaluate condition: • if TRUE go to 2• If FALSE go to 3

Execute statements, and then go to 1Continue with next statement.

The dynamics of “while”Evaluate condition:

• if TRUE go to 2• If FALSE go to 3

Execute statements, and then go to 1Continue with next statement.

1.

2.3.

Page 15: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

“while” structures• It repeats a set of statements while a condition is true.

int speedLimit = 55;int speed = 0;

while ( speed <= speedLimit ) { speed = speed + 1;}// since we don’t want a ticket…speed = speed - 1;

• What is the value of “speed” at this point?

Page 16: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

“while” structures• It repeats a set of statements while a condition is true.

int speedLimit = 55;int speed = 0;

while ( speed < speedLimit ) { speed = speed + 1;}// since we don’t want a ticket…speed = speed - 1;

initialize variablesin conditional

initialize variablesin conditional

1

modify variablesin conditional

modify variablesin conditional

2

Page 17: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

“while” structures• Adding the values of an array of integers

int grades[] = new int[1000];/* the values of the elements are somehow initialized here.*/int i = 0;int sum = 0;

while ( i < grades.length ) { sum += grades[i]; i++;}

System.out.println(“The sum is ” + sum);

Page 18: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

“while” structures: Exercises

• Determine the output of the following methods:

public void foo1() { int i=0; while (i <= 20) { System.out.println( i ); i = i + 4; } }

public void foo2() { int i = 20; while (i > 0) { i = i / 2; System.out.println( i ); }}

Page 19: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

Quiz 4 (parts 1 and 2)1. Write a method named “countDown” that receives an integer

parameter named “number”, and displays (using System.out.println) all numbers from the number down to 0.• For example, if the parameter was 8, the method should

display numbers 7, 6, 5, 4, 3, 2, 1, 0, in this order and with each number in one line.

2. Write a method named “countEven” that receives an integer parameter named “number”, displays (using System.out.println) all even numbers between 0 and the number received, and returns a integer value with the number of even numbers displayed.• For example, if the parameter was 8, the method should

display numbers 2, 4 and 6, in this order and with each number in one line, and return a value of 3 (which is how many even numbers were between 0 and 8).

Page 20: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

3. Write a method named “reverse” that receives an integer parameter named “number” and displays (using System.out.println) the number with all digits reversed. The method should only work with positive parameter values. For example, if the number was 2001, the method should display 1002. (Hint: use modulus by 10 to extract the last digit from the number, and then divide the number by 10 before extracting the next digit).

4. Write a method named “prime” that returns a boolean value indicating whether an integer parameter named number is a prime number (i.e., not divisible by any number except 1 and the number itself). Use only positive integers.

5. Write methods 1-4 on a piece of paper handwritten, NOT typed.

Quiz 4 (parts 3 and 4)

Page 21: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

“for” structures• It (also) repeats statements while a condition is true.

initialstatement

loopcondition

modifystatement

2211 44

33

55The dynamics of “for”

1. Initialize condition variables.2. Evaluate loop condition:

• if TRUE go to 3• If FALSE go to 5

3. Execute statements; then go to 44. Modify condition variables; then go to 25. Continue with next statements.

The dynamics of “for”1. Initialize condition variables.2. Evaluate loop condition:

• if TRUE go to 3• If FALSE go to 5

3. Execute statements; then go to 44. Modify condition variables; then go to 25. Continue with next statements.

for ( ; ; ){ statements;}

Page 22: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

“for” structures: Exercises1. Write a method named “factorial” that calculates the

factorial of an integer parameter named “number” (where factorial is the multiplication of all numbers from 1 to number-1). The method should return an integer number with the result of the factorial, and it should work only with positive numbers (return 0 in the case of non-positive parameter numbers).

2. Write a method named “prime” that returns a boolean value indicating whether an integer parameter named “number” is a prime number (where a prime number is a number that is not divisible without remainder by any other numbers except 1 and the number itself). The method should work only with positive numbers (return false if a negative parameter number is given).Sample list of prime numbers: 2, 3, 5, 7, 11, 13, 19, 23…

Page 23: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

“for” structures: Exercises3. Write a method named “digits” that displays (using

System.out.println) the digits of an integer parameter named “number” separated by dashes (“-”). For example, when receiving the number 1234 as a parameter, the method should display “1-2-3-4”.

• Hints: use an array to store each digit as you extract them using the modulus operator. Since these digits are stored in the array in the inverse order as they are found in the number, you will need to print them backwards. Also, note that the last digit does not have a trailing dash!

Page 24: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

Containers(ArrayList)

Chapter 4

Page 25: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

ArrayList• Like arrays, but have built in operators• Use library (package)

import java.util.ArrayList;• Declare variable

private ArrayList circles;• To create a list

circles = new ArrayList( ); // NOT Circle• To add an element to the list (like Circle c)

circles.add(c)

Page 26: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

More ArrayList methods

• To find the size:circles.size();

• To retrieve an element:circles.get(1); // returns the second element

• To remove an elementcircles.remove(1); // removes the second element

Page 27: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

ArrayList Overview

• Part of Java Containers– Not fixed size– Can add without having index

• ArrayLists, Sets, Maps – Sets have no duplicates and no order– Maps have key and element association

• Containers have same methods: (size, remove)

• Can put in ANY object – No primitives in containers

Page 28: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

More on Containers

• No need to specify type of object:

private ArrayList circles;

circles = new ArrayList( ); // NOT Circle

circles.add(c); • c could be a Circle, a Square, a Student,

ANY object• If c is a Student, c.changeColor(“red”);

will cause runtime error, not syntax error

Page 29: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

ArrayLists are ugly

• for loop with index

for (int i=0;i<circles.size( ); i++) {

Circle c = circles.get(i); // this returns the ith circle

c.changeColor(“red”);

}• Syntax error:

– Incompatible types - found java.Lang.Object but expected Circle

– Object is superclass of all objects

Remember the ()s unlike arrays

Page 30: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

ArrayLists are ugly

• for loop with index

for (int i=0;i<circles.size( ); i++)

{

Circle c = (Circle) circles.get(i); c.changeColor(“red”);

}

• When using containers in the past, always had to cast object when removing them

Cast to class that you put

in there

Page 31: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

ArrayLists and Casting

• Worse, you could put in something that is NOT a circle:

Student s = new Student( );circles.add(s);// more code, then:(Circle) circles.get(i) // where i is s’s index• Runtime error when a circle method is

called• c.changeColor(“red”) // if c is student

Page 32: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

Solution: Java 5 Generics

ArrayList<Circle> circles = new ArrayList<Circle>( );

• Now, syntax error for:

Student s = new Student( );

circles.add(s);• Can’t do it

Page 33: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

More on Java 5 Generics

• And, no casting:

for (int i=0; i<circles.size( ); i++)

{

Circle c = circles.get(i); c.changeColor(“red”);

}

No “(Circle)”

Page 34: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

More on Container Loops

• Containers can use iterators

• New Java 5 for loop

Page 35: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

ClassWork

• Write a class ConcentricCircles that holds an ArrayList of Circles.

• Create a constructor that adds 3 circles to the ArrayList. Alternate black and white colors.

• Write method DrawCircle that draws the circles.

Page 36: Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4

Quiz 5• Write a ConcentricCircle class that has the methods: add and draw.

The class should use an ArrayList using generics to • hold the circles.• The constructor should create one black circle in the middle of the

canvas (150, 150) of size 20 (note: the circle will NOT have an xPosition and yPosition of 150.

• Each additional call to add should add a circle with a diameter 15 larger and still centered around the center of the canvas. It should be white if the previous circle was black and black if the previous circle was white. Have a boolean instance variable to keep track of this.

• Draw should make each circle in the ArrayList visible.• Turn in your ConcentricCircle source code.