Array Slides
Array Slides
Java
AP Computer Science
Conceptual Overview
An array consists of an ordered collection
of similar items.
An array has a single name, and the
items in an array are referred to in terms
of their position within the array.
An array makes it just as easy to
manipulate a million test scores as it
would to work with three test scores.
int[] abc;
abc[1] = 10; // runtime error: null pointer exception
ddd[5] = 3.14;
bbb[5] = true;
ggg[5] = "The cat sat on the mat.";
sss[5] = new Student();
sss[5].setName ("Bill");
str = sss[5].getName() + ggg[5].substring(7);
// str now equals "Bill sat on the mat."
names ages
0 Bill 0 20
1 Sue 1 21
2 Shawn 2 19
3 Mary 3 24
4 Ann 4 20
String searchName =
JOptionPane.showInputDialog("What name do you want to search for?");
for (i = 0; i < name.length; i++)
{
if (searchName.equals(name[i]))
{
correspondingAge = age[i];
break;
}
}
if (correspondingAge == -1)
System.out.println(searchName + " was not found.");
else
System.out.println(searchName + " is " + correspondingAge +
" years old.");
for (int row = 0; row < students.length; row++) //loops thru rows
{
System.out.println("");
System.out.print("These students are in period " + (row+1) + ": " );
for (int col = 0; col < students[0].length; col++) //loops thru columns
{
System.out.print( students[row][col] + ", " );
}
}
Note: You do not have to use these exact students or test scores
StudentTestScores
Create a StudentTestScores class and StudentTestScoresViewer client class:
In the StudentTestScores class, create a method named printTestScores():
This class should keep track of test scores for multiple students. Test scores are integer
values between 0 and 110 (we’ll assume that up to 10 points extra credit could be allowed
on a test).
Create a normal one-dimensional array to keep track of student names. Use an initializer
list to populate this array with 6 student names (6 elements).
Create a two-dimensional array to keep track of multiple test scores per student.
4 tests have been taken by each student.
Each row number of this array will correspond to the index of the student from the “student
names” array you just created.
Each column represents one of the four test scores for the student.
Use an initializer list to populate the test scores for each student.
Write a loop to process the two arrays as follows:
Loop through each student in the student array
For each student, loop through the corresponding test scores for that student
Output the student name and a list of his/her test scores to the console similar to the following.
Also, calculate the average test score for the student:
Bill had test scores of 75, 80, 80, 85. Test average is 80.0
Test with a couple scenarios
EXTRA CREDIT (5 points):
Print the lowest test score (and the name of the person that had it) to the console.
Print the highest test score (and the name of the person that had it) to the console.
Print the class average test score (for all students in the class) to the console.
Working with Arrays
That Are Not Full
One might create an array of 20 ints but
receive only 5 ints from interactive input
(remember the TestScores program).
This array has a physical size of 20 cells
but a logical size of 5 cells currently
used by the application.
From the application's perspective, the
remaining 15 cells contain garbage.
int sum = 0;
for (int i = 0; i < size; i++) // size contains
//the number of items in the array
sum += abc[i];
Show TestScores program at this point Java Concepts 7.1 (Arrays)
Working with Arrays
That Are Not Full
Inserting Elements into an Array
The simplest way to insert a data
element into an array is to place it after
the last populated item in the array.
One must first check to see if there is an
element available (make sure you are not
going over the array’s length) and then
remember to increment the array's logical
size.
The following code shows how to insert
an integer at the end of array abc:
Java Concepts 7.1 (Arrays), 7.7 (Copying Arrays)
Working with Arrays
That Are Not Full
if (size < abc.length)
{
abc[size] = anInt;
size++;
}
When size equals abc.length, the array is full.
The if statement prevents a range error
(ArrayIndexOutOfBoundsException) from
occurring.
Remember that Java arrays are of fixed size when
they are instantiated, so eventually they could
become full.
double sum = 0;
for (int i = 0; i < studentArray.length; i++)
{
sum += studentArray[i].getAverage(); //Send message to object
} //in array
System.out.println("The class average is " + sum / studentArray.length);
cp = copyArray(orig);
Java Concepts 7.7 (Copying Arrays)
EmployeeNames
Create an EmployeeNames class and EmployeeNamesTester client class to do the following:
You are a programmer for a company of 10 employees. The owner of the company only hires
people whose first name begins with the last character of their last name and their middle name
begins with the next-to-last character in their last name (i.e. H. T. Smith or Z. E. Lopez). You have
been given only the last names of each employee and have been asked to generate a list of
employee names using the first and middle initials (i.e. you were given Jones, you need to print S.
E. Jones).
Since your boss is very controlling and wants to make sure that you know how to pass arrays to
methods, he has given you the following strict instructions on how to create the program:
Your EmployeeNames class needs to have a static method named convertName(). This method will be
the only method in this class and should do the following:
The method should accept an array of last names as the input parameter.
The method should return an array of formatted names (first and middle initials and last name)
Loop through the array of last names that is sent to the method.
For each element, it should determine the first initial and middle initial of the name and format it correctly (H. T. Smith)
It should store each of these formatted names as elements in a formatted names array.
After processing all the names, the method should return the formatted names array back to the calling program.
Create a driver program named EmployeeNamesTester. Create a main() method in this class and do the
following in the main() method:
Create an array of employee last names (there are up to 10 employees). You need to populate this array with last names
by either using an initializer list or prompting the user (see extra credit).
Declare and instantiate an array of formatted names that will be used to store the name with first and middle initials.
Call the EmployeeNames.convertName method and pass it the array of last names.
Assign the returned array to the formatted names array you created in the main method.
Loop through the formatted names and print them to the console on separate lines.
EXTRA CREDIT (5 points):
Input the last names instead of using an initializer list and handle the situation where the last names array is not full.