Transcript 3.2

Arrays
• An array is a single variable that holds more than
one value. Each value is called an element, or a
member, of the array.
• subscript notation identifies each element (the first
element is #0)
• General syntax for declaring an array:
Type[] array_Name = new Type[Length];
• There are 3 different ways to populate (put
values into) an array
– Demo: ArrayDemo1
• Once created, the size of an array cannot be
changed
• Trying to access an array element that does not
exist causes an IndexOutOfBounds exception
(see ArrayDemo1)
• .length (with NO parentheses) is the size of an
array, so the last element is # length-1
for-each loop
• When going through (“traversing”) every
element in an array, an efficient way to do so is
by using a for-each loop.
• Syntax:
for (type element : array)
{
// body of loop
}
• Demo: ForEachLoopDemo
• Although an array’s size cannot be changed,
you can replace one array completely with
another array, even if they are of different
sizes.
• Demo: ArrayReplace
Arrays of Objects
• An array is not limited to holding just ints,
or chars, or Strings, etc.
• An array can hold objects.
• Remember, when you connect to
(instantiate)
a class, you create an object, for example:
Numbers x = new Numbers();
• In this example, x is an object.
• Demo: Person, ArrayOfObjectsDemo
• An array can be sent as a parameter to a class, as
well as returned to a client
in a class:
public String[ ] ned (String[ ] stark)
{
stark[2] = “bran”;
return stark;
}
in a client:
stark = objectName.ned(stark); // assume an array called stark
• To find the mode from the elements of an
array, first you must determine the
frequency of each number occurring….
– Demo: ArrayFrequencyDemo
Assignments (**must use arrays**)
• (ArrayScores)
•
Ask the user how many scores they will enter. Then, have them
enter these scores – you must store their answers in an array.
•
Next, in a new loop, calculate the average score, and also display
each grade along with its letter grade – such as:
“Score #3 = 76%, which is a C”
•
•
Finally, display the average score.
P. 376-377 # 1, 2, 4, 5
– For #1 and #2, “reads a number of integers” means that you ask the user
how many integers they will enter, then have them input those integers.
– (Hint for #2: think about how this can be done “behind the scenes,” so that
even if the user enters a negative, the program actually works almost the
same as #1.)