KFUPM, ICS Department 2/3 First Semester 2008 (Term 081)
ICS102: Introduction to Computing Lab13: Arrays of Objects
King Fahd University of Petroleum & Minerals ICS102: Introduction to Computing
Information and Computer Science Department First Semester 2008 (Term 081)
Lab13: Array of Objects
Objectives
Designing and implementing Java programs that deal with:
1. Arrays
- Declaring Arrays’ of Objects.
- Arrays as parameters and return types.
Notes
Syntax for declearing an array.
Examples:
char[] line = new char[80];
String[] word = new String[SIZE];
Book[] book = new Book[3 * 25];
· An array is an object.
· An array has ONLY 1 instant variable, which is named length.
int[] grade = new int[13];
then grade.length has a value of 13.
· An array type can be used as a parameter for a method.
public void method2( double[] a) {
// method body goes here;
}
Then, the method can be called as:
double[] x = new double[500];
method2( x );
· An array type can be used as a return type for a method.
public Car[] multiplayByFactor(int[] x, int factor) {
// method implementation goes here;
}
Exercises
Exercise #01: (SumArrays.java)
Write and test a method called sum2DArray that takes 2 parameters: an int 2D array and a double 2D array then return the sum of them as a double 2D array without changing the original array parameters. (Hint: Assume the 2 array parameters are of the same size.)
Exercise #02: (StudentTest.java)
Suppose you have a Student class as follows:
class Student{
String id;
private double totalScore;
private int numOfQuizes;
public Student(String _id){
id = _id;
totalScore = 0;
}
public double getTotalScore(){
return totalScore;
}
public void addQuiz(double score){
totalScore += score;
numOfQuizes++;
}
public double getAvarage(){
return totalScore / numOfQuizes;
}
public String toString(){
return "Student id : " + id + "\tAvarage Score : " + getAvarage();
}
}
A- Create a TestStudents.java class that have to ask the user to enter the students score student by student. (keep it limited to 3 quizes)
B- Create 1D array of type Student of size 100.
C- Create method addStudent(Student[] old, int index , String id) that takes an old array or empty and add one student to it and return the new array.
The index is the current index of the filled array. (The objective of this method is to fill the student array one by one)
D- Keep adding students until the user enter “n” or “N”. Note: Ask the user every time do you want to add new student ? and based n the answer keep adding or not.
E- Create a method convertTo2DArray(Student[] stu) that takes student array and return a 2D array of type int[][] that has only the id and the correspondent average score.