how do you do the following? find the number of scores within 3 points of the average of 10 scores?...
DESCRIPTION
Objectives: Understand arrays and when to use them. Understand the vocabulary and syntax associated with using arrays. Be able to program using an array of primitives.TRANSCRIPT
How do you do the following?• Find the number of scores within 3 points of the
average of 10 scores?• What kind of a tool do you need?• Today’s notes:• Include the following • Vocabulary• Ideas• Examples• Questions
Java: Arrays
10/19/2015
Objectives:
• Understand arrays and when to use them.• Understand the vocabulary and syntax
associated with using arrays.• Be able to program using an array of
primitives.
When to use Arrays
• Large group of similar information.• Use the information more than once.• Sorting• Tallying, i.e. elections
What is an Array
• An array is a block of consecutive memory locations that hold values of the same data type.
• Individual locations are called array’s elements.
• When we say “element” we often mean the value stored in that element.
1.39
1.69
1.74
0.0
An array of doubles
What is an Array (cont’d)
• Rather than treating each element as a separate named variable, the whole array gets one name.
• Specific array elements are referred to by using array’s name and the element’s number, called index or subscript.
c[0] c[1] c[2] c[3]
1.39
1.69
1.74
0.0 c is array’s
name
When to use an array
• When you are temporarily storing a large group of similar information
• When you need to use the information more than once
• When sorting.
Indices, Subscripts, addresses
• In Java, an index is written within square brackets following array’s name (for example, a[k]).
• Indices start from 0; the first element of an array a is referred to as a[0] and the n-th element as a[n-1].
• An index can have any int value from 0 to array’s length - 1.
Indices (cont’d)
• We can use as an index an int variable or any expression that evaluates to an int value. For example:
a [3] a [k] a [k - 2] a [ (int) (6*Math.random()) ]
Indices (cont’d)• In Java, an array is declared with
fixed length that cannot be changed.• Java interpreter checks the values of
indices at run time and throws ArrayIndexOutOfBoundsException if an index is negative or if it is greater than the (length of the array – 1).
Why Do We Need Arrays?
• The power of arrays comes from the fact that the value of a subscript can be computed and updated at run time.
int sum = 0;sum += score0;sum += score1;…sum += score999;
No arrays:
int n = 1000;int sum = 0, k;
for (k = 0; k < n; k++) sum += scores[k];
With arrays:
1000times!
Why Arrays? (cont’d)• Arrays give direct access (random
access) to any element — no need to scan the array.
if (k == 0) System.out.print (score0);else if (k == 1) System.out.print(score1);else … // etc.
System.out.print(scores[k]);
1000times!
No arrays: With arrays:
Vocab. Check.
• Array• Index• Element• Primitive• Subscript• ArrayIndexOutOfBoundsException
Arrays as Objects
• In Java, an array is an object. If the type of its elements is anyType, the type of the array object is anyType[ ].
• Array declaration:anyType [ ] arrName;
What is arrName?
Arrays as Objects (cont’d)
• As with other objects, the declaration creates only a reference, initially set to null. An array must be created before it can be used.
• One way to create an array:
arrName = new anyType [length] ; Brackets, not parens!
anyType [ ] arrName;
int [] numbers;
numbers = new int [100];
• When an array is created, space is allocated to hold its elements. If a list of values is not given, the elements get the default values. For example:
Declaration and Initialization
int [] scores; scores = new int [10] ;
String [] words;words = new String [10000];
length 10, all values set to 0
length 10000, all values set to null
Initialization (cont’d)
• An array can be declared and initialized in one statement. For example:
int [ ] scores = new int [10] ;
double [ ] gasPrices = { 3.05, 3.17, 3.59 };
String [ ] words = new String [10000];
String [ ] cities = {"Atlanta", "Boston", "Cincinnati" };
The left side creates the pointer, reference, object
The right side creates what is being pointed to, referred
to, …
String [ ] words;
... words = new String [ input.nextInt() ];
double[ ] gasPrices; … gasPrices = new double[ ] { 3.05, 3.17, 3.59 };
Initialization (cont’d)
• Otherwise, initialization can be postponed until later. For example:
Not yet initialized
Not yet initialized
Review
• An array..– Holds a large group of similar information– When you need to use the information more
than once– When you are sorting
• What are some pros and cons of arrays?
Your turn to declare
• Declare arrays to store the following• The names of 15 people• The gpas for each person• The scores of 10, 15, -8, and 14
Array’s Length
• The length of an array is determined when that array is created.
• The length is either given explicitly or comes from the length of the {…} initialization list.
• The length of an array arrName is referred to in the code as arrName.length.
• length is a public field (not a method) in an array object.
• That is why it is not arrName.length().
Initializing Elements• Unless specific values are given in a {…}
list, all the elements are initialized to the default value: 0 for numbers, false for booleans, null for objects.
• If its elements are objects, the array holds references to objects, which are initially set to null.
• Each object-type element must be initialized before it is used.
What do you recall about…• Arrays• Index• Address• ArrayIndexOutOfBoundsException• Can the size of an array change?• What does this line of code do?
– double [ ] gpas = new double [15];• How can you find the number of elements in
an array?
Your turn, in BlueJ• Declare arrays to hold the following
– Ten ages– The names: Mannie, Moe, Jack and Curly– 5 Radio stations
• In BlueJ, Write the code to input values into the ages array.
• Write the code to display the information from the ages array
What do these line of code do?double [ ] gasPrices = { 3.05, 3.17, 3.59 };for (int i=0; i<gasPrices.length;i++) System.out.print(gasPrices[i]+ " ");System.out.println();gasPrices = new double[ ] { 1, 5.9 }; for (int i=0; i<gasPrices.length;i++) System.out.print(gasPrices[i]+ " ");System.out.println();gasPrices = new double[ ] { 4.0, 3.64, 2 , 12};for (int i=0; i<gasPrices.length;i++) System.out.print(gasPrices[i]+" ");System.out.println();
How can you…• Create an integer array called scores that will
hold 10 scores?– int [] scores = new int[10];
• What is the code to get the scores from the user?
How can you …
Find the average of the array declared previously?
Sample Array Codepublic class ArrayDemo {
public static void main(String[] args) {
int [] anArray; // declare an array of integers anArray = new int[10]; // create the array
// assign a value to each array element and print for (int i = 0; i < anArray.length; i++) {
anArray[i] = i; System.out.print(anArray[i] + " ");
} System.out.println();
} }
Can alsoint [] anArray = new int[10];To both declare and create.
Notice the addresses go from 0 to 9,
anArray.length returns the number of values in
the array.
Sample Code initializing the vlaues.// Fig. 7.3: InitArray.java// Initializing the elements of an array with an array initializer.
public class InitArray { public static void main( String args[] ) { // initializer list specifies the value for each element int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings // output each array element's value for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] ); } // end main} // end class InitArray
Note: You do not have to include the
‘new’ line. The compiler
counts the initializers and
sets this up for you!
Program• Input: 10 scores (integers)• Output:
– The high score– The low score– The average– The number of scores within 3 of the average– Push: Show the numbers in order low to high
• Input: 10 scores and calculate the standard deviation
Standard Deviation Example.• Find the standard deviation of 4, 9, 11, 12, 17, 5, 8, 12, 14• First work out the mean (Average, xbar,…): • (4 + 9 + 11 + 12 + 17 + 5 + 8 + 12 + 14)/9 = 10.222• Now, subtract the mean individually from each of the numbers in the question
and square the result. This is equivalent to the (x - xbar)² step. x refers to the values in the question.
• x 4 9 11 12 17 5 8 12 14(x - xbar)² 38.7 1.49 0.60 3.16 45.9 27.3 4.94 3.16 14.3
• Now add up these results (this is the 'sigma' in the formula):• 139.55• Divide by n-1. n is the number of values, so in this case n-1 is 8: • 139.55 / 8 = 17.44• And finally, square root this:• 4.18