Arrays of Primitives
Download
Report
Transcript Arrays of Primitives
Introduction to Programming
with Java, for Beginners
Arrays
What if our Frog (from lab) could say 10
different things?
public class Frog{
private boolean formerPrince;
private String phrase1;
private String phrase2;
private String phrase3;
private String phrase4;
private String phrase5;
private String phrase6;
private String phrase7;
private String phrase8;
private String phrase9;
private String phrase10;
...
1
What a Person could adopt lots of Pets ?
public class Person{
private String name;
private
private
private
private
private
private
private
private
private
private
private
private
private
private
private
private
. . .
Pet
Pet
Pet
Pet
Pet
Pet
Pet
Pet
Pet
Pet
Pet
Pet
Pet
Pet
Pet
Pet
pet1;
pet2;
pet3;
pet4;
pet5;
pet5;
pet6;
pet6;
pet8;
pet9;
pet10;
pet11;
pet12;
pet13;
pet14;
pet15;
2
What if we wanted to store 500 Itoons?
public class IToonList{
private IToon toon1;
private IToon toon2;
private IToon toon3;
private IToon toon4;
private IToon toon5;
private IToon toon6;
private Ttoon toon7;
private IToon toon8;
private IToon toon9;
private Ttoon toon10;
private IToon toon11;
private IToon toon12;
private IToon toon13;
. . .
private IToon toon500;
3
What if we want to store lots of things…
But we don’t want to declare a separate
variable for each one?
That’s what arrays are good for
4
What is an Array?
It’s an easy way to declare lots of variables
that all have the same type.
int[] data;
data = new int[5];
// array of 5 ints
data[0] = 6;
data[1]= 10;
data[2] = 12;
5
Array Elements and Indices
The “data” array has 5 elements. The value of
data[0] is 6
data[1] is 10
data[2] is 12
data[3] is 0
data[4] is 0
The number within square brackets is called an index
The valid indices are 0 thru (array length - 1)
NOTE: Whenever you see square brackets [ ] in a Java
program, it means you’re dealing with an array.
6
An Array is an Object
int[] data;
data is a reference variable
whose type is int[], meaning
“array of ints”. At this point its
value is null.
data = new int[5];
The new operator causes a
chunk of memory big enough for
5 ints to be allocated on the
heap. Here, data is a assigned a
reference to the heap address.
Initially, all five ints are 0. Here,
three of them are assigned other
values.
data[0] = 6;
data[1]= 10;
data[2] = 12;
int[] info = {6, 10, 12, 0, 0};
info = new int[]{6, 10, 12, 0, 0};
7
Using Array Elements in Expressions
An element of an array of ints can be used virtually
anywhere an expression of type int is valid.
Likewise for arrays of other types
int[] data = new int[] {6, 10, 12, 0, 0};
int x = data[0];
data[3] = data[2];
data[4] = data[3] + data[2] * 2;
System.out.println(“data[0] is “ + data[0]);
// note order of operations below:
data[4] = Math.pow(2, data[4]);
8
Accessing an Array’s Length
ArrayName.length gives size of the array
int[] data;
data = new int[5];
data[0] = 6;
data[1]= 10;
data[2] = 12;
// data.length is 5
int result = 0;
for (int i =0; i < data.length; i++){
result = result + data[i];
}
9
Complete the sum(..) method
public class ArrayTool{
/**
* Takes an array of ints as an argument.
* returns the sum of all the integers in the array.
*/
public static int sum ( ?? ) {
}
}
Welcome to DrJava
> int[] data = new int[] {6, 10, 12, 0, 0};
> ArrayTool.sum(data)
28
10
Array Out of Bounds Exceptions
public class ArrayTool{
public static int sum(int[] data){
int sum = 0;
for (int i = 0; i < data.length; i++){
sum = sum + data[i]; // sum += data[i];
}
return sum;
}
public static int sum2(int[] data){
int sum = 0;
for (int i = 0; i <= data.length; i++){ // error!
sum = sum + data[i]; // sum += data[i];
}
return sum;
}
}
> ArrayTool tool = new ArrayTool();
> int[] data = new int[] {6, 10, 12, 0, 0};
> tool.sum(data)
28
> tool.sum2(data)
ArrayIndexOutOfBoundsException:
11
Examples of Arrays of Other Primitive Types
double[] temps;
temps = new double[24];
temps[0] = 78.5;
temps[1] = 84.2;
boolean[] answers = new boolean[6];
. . .
if (answers[0]){ //do something }
char[] buffer = new char[500];
open a file for reading
while (more chars in file & buffer not full)
buffer[i++] = char from file
12
Declaring & Initializing Arrays of Primitives
int[ ] info1 = { 2000, 100, 40, 60};
int[ ] info2 = new int[ ]{ 2000, 100, 40, 60};
char[ ] choices1 = { 'p', 's', 'q'};
char[ ] choices2 = new char[ ]{ 'p', 's', 'q'};
double[ ] temps1 = {75.6, 99.4, 86.7};
double[ ] temps2 = new double[ ] {75.6, 99.4, 86.7};
13
Complete this method
public class ArrayTool{
/* Returns true if all integers in the
data array
* are positive, false otherwise.
*/
public static boolean allPositive(int[] data){
}
14
One Solution
public class ArrayTool{
/* Returns true if all integers in the
data array
* are positive, false otherwise.
*/
public static boolean allPositive(int[]
data){
for (int i = 0; i < data.length; i++){
if (data[i] <= 0) {
return false;
}
}
return true;
}
}
15
Another Solution
public class ArrayTool{
/* Returns true if all integers in the
data array
* are positive, false otherwise.
*/
public static boolean allPositive(int[]
data){
boolean result = true;
for (int i = 0; i < data.length; i++){
if (data[i] <= 0) {
result = false;
break; //break is java keyword
}
}
return result;
}
16
break statement
For example on the previous slide:
Terminates the for loop if the value found is
negative
Used only with loop structures
Rule: Terminates the innermost for, while
17
2D Arrays
Array
can have 2, 3, or more dimensions
When declaring a variable for such an array, use a pair of
square brackets for each dimension
For 2D arrays, the elements are indexed [row][column]
Remember “RC” [row][column]
char[][] board;
board = new char[3][3]; // 3
columns
board[0][0] = ‘O’; // row 0,
board[1][1] = ‘X’; // row 1,
board[0][1] = ‘X’; // row 0,
rows, 3
column 0
column 2
column 1
18
Nested Loops
A “nested
loop” occurs when one loop is inside another
Examples
// doubly nested loop
for (expr; condition; expr){
..
for (expr; condition; expr){
..
}
}
// triply nested loop
while(condition){
for(expr; condition; expr){
while(condition){
…
19
Nested Loops
“Doubly
nested”: one loop inside another
“Triply nested”: a loop within a loop within a loop
Java does not place a limit on nesting levels
Deeply nested loops can be hard to maintain/debug
Fix: create a “helper method” to handle inner loops and
call that method in an outer loop
20
Processing a 2D Array
Use a doubly-nested for-loop to process a 2D array
In this example we know the number of rows (3) and columns (5)
In general, it’s better not to use “magic numbers” (here the 3 and 5) in the
loop. It’s better to write code that handles the general case (see next slides)
char[][] data = new char[3][5];
for (int row = 0; row < 3; row++){
for (int col = 0; col < 5; col++){
System.out.print(data[row][col] + ‘\t’);
}
System.out.println();
}
21
Processing a 2D Array (cont.)
Most 2D arrays have a uniform number of rows and colums
An “n x m” array (an “n by m array”) has n rows and m columns
// prints an array with dimensions “nWeeks x nDays”
public static void print(double[][] temps,int nWeeks, int
nDays){
for (int row = 0; row < nWeeks; row++){
for (int col = 0; col < nDays; col++){
System.out.print(temps[row][col] + “\t”);
}
System.out.println();
}
}
22
Processing a 2D Array (cont.)
This illustrates a general purpose way to print a 2D array
It works even for “ragged” arrays, whose row lengths vary.
public static void printArray(int[][] data){
if (data == null || data.length == 0)
return;
for (int row = 0; row < data.length; row++){
for (int col = 0; col < data[row].length; col++){
System.out.print(data[row][col] + “\t”);
}
System.out.println();
}
}
23
Ragged Array
Row lengths vary.
Motivation: save space
>
>
>
>
>
>
3
>
6
>
2
>
>
>
>
2
>
6
>
3
int[] one = {1,2,3}
int[] two = {1,2,3,4,5,6}
int[] three = {1,2};
int[][] data = {one, two, three}
data[0].length
data[1].length
data[2].length
data[0] = three;
data[1] = two;
data[2] = one;
data[0].length
data[1].length
data[2].length
24