Chapter 10

Chapter 10
Arrays
Learning Java through Alice
© Daly and Wrigley
Objectives
• Declare and use arrays in programs.
• Access array elements within an array.
• Calculate the sum, largest number, smallest
number, and average of a group of numbers by
using an array.
• Setup a program to store the arguments from
command line into an array.
2
Learning Java through Alice
© Daly and Wrigley
Declaring an Array
Array - group of contiguous memory locations
that all have the same name and the same type.
Declaring an array:
int [ ] temp; // an integer array called temps
boolean[ ] hostilePeople; // an array of hostilePeople
String difficultWord [ ]; // an array of difficultWords
double examScore[ ]; // an array of examScores
3
Learning Java through Alice
© Daly and Wrigley
Creating Array Objects
int [ ] temp = new int [ 250 ] ;
String [ ] reindeerName = { "Dasher", "Dancer", "Prancer",
"Vixen", "Comet", "Cupid", "Donner", "Blitzen" } ;
4
Learning Java through Alice
© Daly and Wrigley
Length of Array
String n [ ] = { "Mary", "John", "Susan", "Robert" };
int x = n.length; // where n is the name of the array
n[ 0 ] = "Mary";
n[ 1 ] = "John";
n[ 2 ] = "Susan";
n[ 3 ] = "Robert";
The length of the array called n is 4.
n[2] is "Susan" instead of "John" as you might expect.
5
Learning Java through Alice
© Daly and Wrigley
Example Array Program
public static void main (String args[ ] ){
int number =5;
int myArray [ ] = new int[10]; // declares integer array of 10 elements
for (int i = 0; i <10; i ++) {
myArray[i] = number; // puts 5, 10, 15 into elements of myArray
System.out.println("The " + i + " element of the array is " + myArray [ i ] );
number += 5;
}
The 0 element of the array is 5
}
The 1 element of the array is 10
The 2 element of the array is 15
The 3 element of the array is 20
The 4 element of the array is 25
The 5 element of the array is 30
The 6 element of the array is 35
The 7 element of the array is 40
The 8 element of the array is 45
The 9 element of the array is 50
6
Learning Java through Alice
© Daly and Wrigley
7
Another Way of Writing the
Previous Program
public static void main (String args[ ] ) {
int myArray [ ] = new int[10]; // declares integer array of 10 elements
for (int i = 0, number=5; i<10; i ++, number+=5) {
myArray[i] = number; // puts 5, 10, 15 into elements of myArray
System.out.println("The " + i + " element of the array is " + myArray[i] );
}
}
Learning Java through Alice
© Daly and Wrigley
Summing Numbers
sum = sum + a;
sum= sum + b;
sum = sum + c;
sum = sum + d;
sum = sum + e;
OR
sum = sum + a + b + c + d + e;
OR
If the values were in an int array called x, we could do the same thing as follows:
for ( i = 0; i < 5 ; i++) {
sum = sum + x [ i ];
}
8
Learning Java through Alice
© Daly and Wrigley
Drawing Polygons
9