In the last lab, we worked with two-dimensional images, which contain large numbers of individual pixel values. Rather than declaring one individual variable for each pixel value, programming languages provide data structures called arrays for storing such data sets. In this lab, we’ll work with arrays and with file input/output.
Arrays provide general purpose data storage for sets of similar objects. Consider the problem of representing and working with a set of numbers representing the number of hours worked by each individual employee in an organization.
|
int barHeight = 25,
barWidthUnit = 5,
labelWidth = 25;
int[] hours = { 27, 32, 40, 10, 18 };
void setup() {
size(barWidthUnit * 40 + labelWidth + 1,
barHeight * hours.length + 1);
PFont font = loadFont("Calibri-12.vlw");
textFont(font);
textAlign(RIGHT, TOP);
noLoop();
}
void draw() {
for (int i = 0; i < hours.length; i++) {
// Draw the bar.
fill(255);
rect(labelWidth, i*barHeight,
hours[i] * barWidthUnit, barHeight);
// Draw the label
fill(0);
text("#" + (i+1),
labelWidth-5, i*barHeight+5);
}
}
|
Declaration/initialization patterns:
type[] identifier;
type[] identifier = new type[size];
type[] identifier = { valueList };
Access pattern: identifier[index]
|
This example shows the hours worked by each employee, all of
which are stored in a single array, hours. The array
is initialized using a literal array value ({ 27, 32, 40,
10, 18 }), it’s length is specified by the
length variable (hours.length), and its
individual elements are accessed using the subscript operator
(hours[i]).
Average: 25 Maximum Value: 40 Minimum Value: 10
Large data sets must generally be stored permanently, either in a database or even a simple text file. We can rewrite the program given above so that it loads the hours data from a file.
27 32 40 10 18 17 5 22 35 37 |
int barHeight = 25, barWidthUnit = 5, labelWidth = 25;
String[] hours;
int hoursInt;
void setup() {
hours = loadStrings("hours.txt");
size(barWidthUnit * 40 + labelWidth + 1, barHeight * hours.length + 1);
PFont font = loadFont("Calibri-12.vlw");
textFont(font);
textAlign(RIGHT, TOP);
noLoop();
}
void draw() {
for (int i = 0; i < hours.length; i++) {
hoursInt = int(hours[i]);
// Draw the bar.
fill(255);
rect(labelWidth, i*barHeight, hoursInt * barWidthUnit, barHeight);
// Draw the label.
fill(0);
text("#" + (i+1), labelWidth-5, i*barHeight+5);
}
}
|
This program is similar to the one shown above, but this one loads the hours data from a file, which entails a number of changes:
hours.txt).loadStrings() command.Submit your code for the lab exercises and include a screen capture for each.