Arrays and Further Control Structures

Download Report

Transcript Arrays and Further Control Structures

Grouping Related Items
• We often need to group together related
items of data.
– Cards in a pack.
– Ships in a port.
• Java provides two distinct facilities:
– Fixed-size arrays.
– Flexible-size collection classes (java.util).
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
1
Problems That Arrays Solve
class YearlyRainfall {
public int meanMonthlyRainfall(){
return (getJan()+getFeb()+getMar()+getApr()+
getMay()+getJun()+getJul()+getAug()+
getSep()+getOct()+getNov()+getDec()) /
numMonths;
}
public int getJan(){
return Jan;
}
...
private static final int numMonths = 12;
private int Jan, Feb, Mar, Apr, May, Jun,
Jul, Aug, Sep, Oct, Nov, Dec;
}
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
2
Arrays for Primitive-Types
class YearlyRainfall {
...
// Fixed size of the rainfall array.
private static final int numMonths = 12;
// Declare an attribute to hold the monthly
// rainfall figures.
private int[] rainfall = new int [numMonths];
}
• Square bracket notation is distinctive of arrays:
• Type: int[]
• Construction: new int[...]
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
3
Arrays for Objects
class CardGame {
...
// There are four distinct suits in this game.
final int numSuits = 4;
// An array for the names of the distinct suits.
private String[] suitNames = new String[numSuits];
}
• NB: No String objects are created. Only a
container for Strings.
• Each location is initialized to null.
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
4
Array Lengths
• The length of an array is fixed on
construction.
• Each array object has a public final
length attribute.
• The individual elements of an array are
always indexed from zero to (length-1).
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
5
Indexing an Array
// Store the rainfall figure for January.
rainfall[0] = 30;
...
// Compare the December and November figures.
if(rainfall[11] > rainfall[10]){
System.out.println(
"December was wetter than November.");
}
...
// Correct an error of 1 millimeter in March's
// rainfall total.
rainfall[2]++;
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
6
Accessors for Array Attributes
class YearlyRainfall {
...
// Return a reference to the array.
public int[] getRainfall(){
// Independent copy not returned!
return rainfall;
}
...
// Fixed size of the rainfall array.
private static final int numMonths = 12;
// Declare an attribute to hold the monthly
// rainfall figures.
private int[] rainfall = new int [numMonths];
}
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
7
Mutators for Array Attributes
class Polyline {
public Polyline(Point[] p){
setPoints(p);
}
...
public void setPoints(Point[] p){
if(p != null){
// Independent copy not taken!
points = p;
}
}
private Point[] points = null;
}
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
8
Initializing Arrays
class AssignmentMonitor {
...
// Differentially weight the assignments.
private int[] assignmentWeights = {
1, 2, 1, 5, 1,
};
private final int numAssignments =
assignmentWeights.length;
}
• No new required.
• Terminating semicolon.
• Optional final comma.
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
9
Further Initializer Examples
String[] suitNames = {
"Spades", "Hearts", "Diamonds", "Clubs"
};
Point[]
new
new
new
new
};
vertices = {
Point(0,0),
Point(0,1),
Point(1,1),
Point(1,0),
YearlyRainfall y2k = new YearlyRainfall(
new int[]{10,10,8,8,6,4,4,0,4,4,7,10,});
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
10
Using For Loops with Arrays
public int totalRainFall(){
// Obtain the data values.
final int[] monthlyValues = getRainfall();
int totalRain = 0;
final int numMonths = monthlyValues.length;
for(int month = 0; month < numMonths; month++){
totalRain += monthlyValues[month];
}
return totalRain;
}
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
11
Iterating over an Array in
Reverse
public void printInReverse(){
final double[] numbers = getMarks();
for(int index = numbers.length-1; index >= 0;
index--){
System.out.print(numbers[index]+" ");
}
System.out.println();
}
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
12
Initializer Blocks
private final int numSeats = 150;
// The status of seats in a theater.
// true means the seat is free, false means occupied.
private boolean[] seatStatus = new boolean[numSeats];
{
// All seats are free to start with.
for(int i = 0; i < numSeats; i++){
seatStatus[i] = true;
}
}
• Static initializers are available to initialize
static fields.
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
13
The Main Method Array
Argument
• Used to access command line argument
values:
– java PrintArguments x y z
• The strings "x", "y" and "z" are placed in
the main method's args argument.
• If there are no arguments, the length of args
is zero.
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
14
Using Command Line Arguments
class LookupWords {
public static void main(String[] args) {
GlossaryManager glossary =
new GlossaryManager();
for(int n = 0; n < args.length; n++){
System.out.println("Looking up "+args[n]);
System.out.println(
glossary.definition(args[n]));
}
}
}
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
15
Copying Arrays
// Make a copy of the Point data.
public void setPoints(Point[] p){
if(p != null){
final int numPoints = p.length;
points = new Point[numPoints];
// Copy from p to points.
System.arraycopy(p,0,points,0,numPoints);
}
}
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
16
Searching an Unsorted Array
• We often need to search an array for a
particular item of data.
• The data is often unsorted.
• The item might or might not be present.
– Care must be taken not to search beyond the
end of the array.
– We need to decide how to return a found item.
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
17
Search with Multiple Returns
public int indexOf(int[] numbers,int value){
final int notPresent = -1;
for(int index = 0; index < numbers.length;
index++){
if(numbers[index] == value){
return index;
}
}
// We did not find it.
return notPresent;
}
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
18
Search with a Single Return
public int indexOf(int[] numbers,int value){
final int notPresent = -1;
int index = 0;
boolean found = false;
while((index < numbers.length) && !found){
if(numbers[index] == value){
found = true;
}
else{
index++;
}
}
return found ? index : notPresent;
}
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
19
The Arrays Class
• Defined in the java.util package.
• Contains static methods for manipulating
arrays:
– binarySearch: search for a value.
– equals: compare the contents of two arrays.
– fill: fill an array with a particular value.
– sort: sort the contents of an array.
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
20
Multi-Dimensional Arrays
• Arrays of multiple dimensions are possible.
– 2D grid, for a board game such as chess.
– 3D cube structure, etc.
• Multi-dimensional arrays are regarded as
being arrays of arrays.
• Non-rectangular structures are possible.
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
21
2D Array Construction
final int numRows = 10, numCols = 5;
double[][] matrix = new double[numRows][numCols];
double[][] grid = new double[numRows][];
for(int row = 0; row < grid.length; row++){
grid[row] = new double[numCols];
}
char[][] hiddenWord = {
{ 'd', 'g', 'i', 'b' },
{ 'e', 'i', 'u', 'm' },
{ 't', 'a', 's', 'a' },
};
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
22
Non-Rectangular Arrays
final int numRows = 5;
int[][] triangle = new int[numRows][];
for(int row = 0; row < numRows; row++){
triangle[row] = new int[row+1];
}
int[][] pascalsTriangle = {
{1},
{1,1},
{1,2,1},
{1,3,3,1},
};
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
23
Further Control Statements
• Java defines several further statements that
affect a program's flow of control.
– The Switch Statement
– The Break Statement
– The Continue Statement
• Statements may also be labelled.
– We rarely use this feature.
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
24
The Switch Statement
• An integer expression is used to select a
case label.
• Case labels are integer constant expressions.
• A default label provides a no-match option.
• Labels mark statements to be executed on
selection.
– A break statement is used to end a case.
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
25
The Switch Statement (cont.)
public void menuAction(char choice){
switch(choice){
case 'd':
delete();
break;
case 'i':
insert();
break;
case 'h':
help();
break;
default:
System.out.println("Unknown command: "+choice);
break;
}
}
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
26
The Break Statement
public int indexOf(int[] numbers,int value){
final int notPresent = -1;
int index;
boolean found = false;
for(index = 0; index < numbers.length; index++){
if(numbers[index] == value){
found = true;
// Leave now - before index is incremented.
break;
}
}
return found ? index : notPresent;
}
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
27
The Continue Statement
public void skipPrinting(int x, int y, int z){
for(int num = 1; num <= 100; num++){
if((num % x) == 0){
continue;
}
if((num % y) == 0){
continue;
}
if((num % z) == 0){
continue;
}
// This one isn't divisible by them.
System.out.println(num);
}
}
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
28
Labeled Statements
• Any statement may be preceded by a label:
– identifier:
• Labels may be the target of break and
continue statements.
– There is no goto statement in Java.
• This simplifies breaking out of deeply
nested loops.
– This feature should be used with caution.
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
29
Review
• Arrays make it possible to group related items
in a single object.
• An array's length is fixed on construction.
• Arrays may have multiple dimensions.
• The Switch, Break and Continue statements
provide further flow control capabilities.
• Labeled statements should be used sparingly.
OOP with Java, David
J. Barnes
Arrays and Further Control Structures
30