Top Banner
French Territory of St. Pierre CSE 114 – Computer Science I Arrays
22

French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

Dec 31, 2015

Download

Documents

Alan Franklin
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

French Territory of St. Pierre

CSE 114 – Computer Science IArrays

Page 2: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

Arrays• An array is an single-named and ordered collection of

data values of the same type.– Why is this important?

• We can store multiple data values (primitive types or objects) easily• We can add to, change, remove from, and refer to this data dynamically

• Declaration of 7 doubles and 100 ints:double score1, … score7;int grade1, grade2, … grade100;

• Declaration/Instantiation of size of array:double[] score;score = new double[7];int[] grade = new int[100];

Reserves memory for this much data

Page 3: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

double[] score;

score = new double[7];

Arrays in Memory

0 1 2 … 99

grade:

0 1 2 3 4 5 6

score:

indexes

values

int[] grade = new int[100];

Page 4: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

int index;

for (index=0; index<7; index++)

score[index] = 6.0;

• Assign values to and access values from array variables using a subscript (index):

grade[12] = 79;

grade[13] = grade[12] + 10;

Array assignments

89 …

0 12 … 99

grade: 79…

… 13

6.0

0 1 2 3 4 5 6

score: 6.0 6.0 6.06.0 6.0 6.0

• NOTE: Array subscripts start with 0!!!! An array of size N has subscripts 0, 1, …, N-1.

Page 5: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

More about Arrays• Array size is static (cannot change after instantiation)• BUT array size does not have to be defined with a constant:

int[] grade;int numGrades;System.out.println ("How many grades do you have?");numGrades = keyboard.nextInt();grade = new int[numGrades];

• Initializing arrays:double[] price = {1.25, 3.15, 2.08};int[] areaCode = new int[10];int j;for (j=0; j<10; j++) areaCode[j]=631;

• What’s wrong with this?for (j=0; j<=10; j++) areaCode[j]=631;

ArrayIndexOutOfBoundsException

Page 6: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

Arrays and Objects• An array is an object (basically):

int[] grade = new int[5];

grade[0]

grade[1]

grade[2]

MEMORY

grade

etc…

• public instance variable: length• length represents the capacity of an array

for (j=0; j<grade.length; j++)

grade[j] = 100-j;

100

99

98

Page 7: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

Subscript out of Range Error

• Using a subscript larger than length-1 or smaller than 0 causes a run time (not a compiler) error– an ArrayIndexOutOfBoundsException is

thrown• you need to fix the problem and recompile your code

• Other programming languages, e.g. C and C++, do not even cause a run time error!– one of the most dangerous characteristics of these

languages is that they may allow out of bounds array indexes.

Page 8: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

Array length• length is specified when an array is created with new

– determines the amount of memory allocated

– determines the maximum number of elements (capacity)• storage is allocated whether or not the elements are assigned values

• What would be the output?double[] score = new double[7];

System.out.println(score.length);

• The length is set when an array is constructed and cannot be changed unless the array is _______________

• When an array is reconstructed all data is lost.

7

reconstructed.

Page 9: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

Array size• The size of a data structure refers to the number of valid elements that are

in the structure (like an array)– There is no automatic mechanism to detect how many elements have been

placed in an array. So what should we do?• You, the programmer need to keep track!

int numGrades = 0;int[] grade = new int[100];char input;do{ System.out.print("Enter a grade: " ); grade[numGrades] = Keyboard.readInt();numGrades++;

System.out.print("Continue? (y/n) "); input = keyboard.nextChar();} while (input != 'n');// HOW MANY ELEMENTS ARE THERE NOW? numGrades

Page 10: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

Parameter Passing and Arrayspublic class Exchange

{ public static void swap(int x, int y)

{ int temp = x;

x = y;

y = temp;

}

}

OUTPUT: 1 3 5 7 9 - the swap doesn’t work! WHY?ints are Call-by-Value!

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

{ int index;int[] num = {1, 3, 5, 7, 9};Exchange.swap(num[1], num[3]);for (index=0; index<num.length; index++)

System.out.print(num[index] + " ");System.out.println();

}}

Page 11: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

Parameter Passing and Arrays (cont’d)public class Exchange

{ public static void swap(int[] number, int a, int b)

{ int temp = number[a];

number[a] = number[b];

number[b] = temp;

}

}

OUTPUT: 1 7 5 3 9 IT WORKS! WHY?Arrays are Call-by-Reference!

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

{ int index;int[] num = {1, 3, 5, 7, 9};Exchange.swap(num, 1, 3);for (index=0; index<num.length; index++)

System.out.print(num[index] + " ");System.out.println();

}}

Page 12: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

Another Game-Playing Objectpublic class PlayingCard{

private char suit;private int rank;

public PlayingCard(char initSuit, int initRank){

if ( ( initSuit == ‘C’ || initSuit ==‘D’|| initSuit == ‘H’ || initSuit ==‘S’ )&& ( initRank >= 1 && initRank <= 13 ) )

{suit = initSuit;rank = initRank;

    } }public char getSuit() { return suit; }public int getRank() { return rank; }

}

Page 13: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

PlayingDeck using an Array of Objectspublic class PlayingDeck

{

private PlayingCard[] deck;

private int numCards = 52;

public PlayingDeck()

{

int cardNum = 0;

int suitNum, rankNum;

char suitChar;

deck = new PlayingCard[numCards];

Page 14: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

    // deck of cards is NOT CREATED YET!!!for (suitNum=1; suitNum<=4; suitNum++){switch(suitNum){case 1: suitChar=‘C’; break;case 2: suitChar=‘D’; break;case 3: suitChar=‘H’; break;case 4: suitChar=‘S’; break;}for (rankNum=1; rankNum<=13; rankNum++){deck[cardNum] = new PlayingCard(suitChar, rankNum);cardNum++;}}

  // NOW IT IS!!!  }

  // Other methods here}

Page 15: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

Arrays and Java

• Arrays are used similarly in most high-level languages• Array: more than a primitive type, less than an object

– methods are invoked by their special subscript notation [i]• most programmers do not even think of them as methods

– an array variable stores a memory address• works like objects when used as method arguments and return types

– arrays do not have or use inheritance

• Arrays are a natural fit for loops, especially for loops• JDK has class implementations, but you may not use them

in this course:– Array, ArrayList, Arrays

Page 16: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

Using == with arrays

if(b == a)o.println("a equals b");

else o.println("a does not equal b");

The output for this code will be "a does not equal b" because the addresses of the arrays are not equal.

a

a[0]

a[1]

a[2]

etc…

b

b[0]

b[1]

b[2]

PrintStream o = System.out;

int i;

int[] a = new int[3];

int[] b = new int[3];for(i=0; i < a.length; i++) a[i] = i;for(i=0; i < b.length; i++) b[i] = i;

0

1

2

0

1

2

MEMORY

etc…

Page 17: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

Methods that Return an Array• Another example of using reference (address)• Actually, the array is not returned.

– The address of the array is returned

• Example: vowels() method constructs and returns an arraypublic static char[] vowels(){ char[] newArray = new char[5]; newArray[0] = 'a'; newArray[1] = 'e'; newArray[2] = 'i'; newArray[3] = 'o'; newArray[4] = 'u'; return newArray;}public static void main(String args[]){

char[] c = vowels(); for(int i = 0; i < c.length; i++) System.out.print(c[i]);}

Page 18: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

• The heading for the main method shows a parameter that is an array of Strings:

public static void main(String[] args)• When running a program from the command line, words after the

class name are passed to the main method in the args array.

java TestProgram Josephine Student

• For example, if the output from the command line were sent to:

Arguments for the main Method

public static void main(String[] args){ System.out.println(“Hello “ + args[0] + “ “ + args[1]);}

Hello Josephine Student•Output:

Page 19: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

null

null

null

null

null

cities[0]

cities[1]

cities[2]

cities[3]

cities[4]

cities

etc…

MEMORY

etc…

Example of a Partially Filled Array

Garbage

values

//counter has a value of 3//cities.length has a value of 5

int counter = 0;

cities[0] = “Boston”;

counter++;

cities[1] = “El Paso”;

counter++;

cities[2] = “Denver”;

counter++;

char c = cities[3].charAt(1);

NullPointerException

Runtime Error!

“Boston”

“El Paso”

“Denver”

String[] cities = new String[5];

Last element,counter - 1

Page 20: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

Multidimensional Arrays• An array can have more than one "dimension" (subscript)• Construction:

int numExams = 5;int numStudents = 10;int[][] grade = new int[numExams][numStudents];

• Assigning Values: grade[1][6] = 92;• Accessing Values: int num = grade[1][6];• A 2-D array corresponds to a table or grid

– one dimension is the row– the other dimension is the column– cell: an intersection of a row and column– an array element corresponds to a cell in the table

Page 21: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

Multidimensional Arrays (cont’d)

• Calculate the average grade on Exam 0.

sum = 0;

for (i=0; i<10; i++)

sum += grade[0][i];

average = Math.round(sum/10.0);

• A 2-dimensional array is really an array of arrays. (Each row is an array.)

• Each row does not have to have the same number of elements. ("ragged array")

Page 22: French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

Multidimensional Arrays (cont’d)

• Calculate the average grade over all exams:

int rows = 5, columns = 10;

int [][] grade = new int[rows][columns];

double sum = 0.0, average = 0.0;;

for (int i=0; i<rows; i++)

for (int j=0; j<columns; j++)

sum += grade[i][j];

average = Math.round(sum/(rows * columns));