Programming and Problem Solving with Java

(やまだぃちぅ) #1
10.8 Testing and Debugging | 511

whose components are arrays, arrays whose components are objects, arrays whose com-
ponents are strings, and so forth. When we use arrays of objects, confusion can arise about
precisely where to place the operators for array element selection ([]) and class field se-
lection (.).
To summarize the correct placement of these operators, let’s use a StudentRecclass
where the data fields are defined as follows:

classStudentRec
{
String stuName; // Student's name
float gpa; // Student's grade point average
int[] examScores = new int[4]; // There are four exams
char courseGrade; // A, B, C, D, or F
...
}

If we declare a variable of type StudentRecand an array of type StudentRec

StudentRec student = newStudentRec();
StudentRec[] members = newStudentRec[ 100 ];

the following chart shows how to access the fields of student. Recall that the dot opera-
tor is a binary (two-operand) operator; its left operand is a class variable or class name,
and its right operand is a field. The []operator is a unary (one-operand) operator; it comes
immediately after an expression denoting an array:

Expression Item Denoted Meaning


student


student.stuName


student.gpa


student.examScores


student.examScores[ 0 ]


student.examScores[ 4 ]


student.courseGrade


members[ 0 ]


members[ 0 ].stuName


members[ 0 ].gpa


members[ 0 ].examScores


members[ 0 ].examScores[ 1 ]


A StudentRecobject
A string
A real number
An array of int
An integer
Crash!! Index out of range
A character
A StudentRecobject
A string
A real number
An array of int

An integer

A single student
A name
A GPA

The first exam score

The first student
The name of the first student
The GPA of the first student
The exam scores for the first
student
The second score for the first
student
Free download pdf