0% found this document useful (0 votes)
2 views

CSC245 Lecture 5

The document provides a comprehensive overview of arrays, including their definition, declaration, creation, and usage in programming. It covers various aspects such as enhanced for statements, passing arrays to methods, and case studies demonstrating practical applications like grade storage and survey analysis. Additionally, it highlights common programming errors and best practices related to arrays.

Uploaded by

armajd676
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CSC245 Lecture 5

The document provides a comprehensive overview of arrays, including their definition, declaration, creation, and usage in programming. It covers various aspects such as enhanced for statements, passing arrays to methods, and case studies demonstrating practical applications like grade storage and survey analysis. Additionally, it highlights common programming errors and best practices related to arrays.

Uploaded by

armajd676
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Review - Arrays

02/05/2019 DIANA HAIDAR 1


Outline
 Introduction to Arrays
 Declaring and Creating Arrays
 Examples using Arrays
 Enhanced for Statement
 Passing Arrays to Methods
 Case Study: Class GradeBook using an Array to Store Grades
 Multidimensional Arrays
 Case Study: class GradeBook using a Two-Dimensional Array
 Variable-Length Arguments Lists
 Using Command-Line Arguments

02/05/2019 DIANA HAIDAR 2


Introduction to Arrays
 Arrays are data structures consisting of related data items of
the same type.
 An array is a group of variables (called elements or
components) containing values that all have the same type
(primitive types or reference types).
 Arrays are fixed-length entities -- they remain the same length
once they are created.
 Arrays are objects, so they are considered reference types.
 A program refers to an element in the array with an array-
access-expression that includes the name of the array followed
by the index of the particular element in square brackets ([ ]).

 c.length accesses array c’s length


 c has 12 elements ( c[0], c[1], …, c[11] )
The value of c[0] is –45

02/05/2019 DIANA HAIDAR 3


Introduction to Arrays
 An index (also called subscript) must be
 a non-negative integer c[ 11 ]; or
 an integer expression a = 5; b = 6; c[ a + b] += 2;
 The first element in an array has index zero.
 Common programming error:
Using a value of type long as an array index results in a compilation error. An index must be an int value or a
value of a type that can be promoted to int -- namely, byte, short or char, but not long.

02/05/2019 DIANA HAIDAR 4


Declaring and Creating Arrays
 Arrays are objects that occupy a space in memory, and are created with keyword new.
 Example:

 Common programming error: In an array declaration, specifying the number of elements in the square
brackets of the declaration (e.g., int c[ 12 ];) is a syntax error.

02/05/2019 DIANA HAIDAR 5


Declaring and Creating Arrays
 Good programming practice: For readability, declare only one variable per declaration. Keep each
declaration on a separate line, and include a comment describing the variable being declared.

 Common programming error: Declaring multiple array variables in a single declaration can lead to subtle
errors.
 Consider int[ ] a, b, c;.
 If only a is intended to be an array variable, and b and c are intended to be individual int variables, then
this declaration is incorrect.
 int a[ ], b, c; would achieve the desired result.

02/05/2019 DIANA HAIDAR 6


Examples using Arrays
1 // Fig. 7.2: InitArray.java
2 // Creating an array.
1. Creating and Initializing an Array
3
4 public class InitArray
5 {
6 public static void main( String args[] )
7 {
8 int array[]; // declare array named array
9
10 array = new int[ 10 ]; // create the space for array
11
12 System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings
13
14 // output each array element's value
15 for ( int counter = 0; counter < array.length; counter++ )
16 System.out.printf( "%5d%8d\n", counter, array[ counter ] );
17 } // end main
18 } // end class InitArray

Index Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0

02/05/2019 DIANA HAIDAR 7


Examples using Arrays
2. Using an Array Initializer 1 // Fig. 7.3: InitArray.java
2 // Initializing the elements of an array with an array initializer.
 An array initializer is a comma-separated list 3
of expressions (called an initializer list) 4 public class InitArray
enclosed in braces ({ }). 5 {
6 public static void main( String args[] )
 The compiler encounters an array 7 {
declaration that includes an initializer list. 8 // initializer list specifies the value for each element
9 int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
 The compiler counts the number of 10
initializers in the list to determine the size of 11 System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings
the array. 12
13 // output each array element's value
 Does not require keyword new to create 14 for ( int counter = 0; counter < array.length; counter++ )
the array object. 15 System.out.printf( "%5d%8d\n", counter, array[ counter ] );
16 } // end main
17 } // end class InitArray

Index Value
0 32
1 27
2 64
3 18
creates a 10-element array with index values 0, 1, 2, 4 95
…, 9 5 14
6 90
7 70
8 60
9 37

02/05/2019 DIANA HAIDAR 8


Examples using Arrays 1 // Fig. 7.4: InitArray.java
2 // Calculating values to be placed into elements of an array.
3
3. Calculating a Value to Store in Each 4 public class InitArray
Array Element 5 {
6 public static void main( String args[] )
 Creates a 10-element array and assigns 7 {
8 final int ARRAY_LENGTH = 10; // declare constant
to each element one of the even 9 int array[] = new int[ ARRAY_LENGTH ]; // create array
integers from 2 to 20. 10
11 // calculate value for each array element
12 for ( int counter = 0; counter < array.length; counter++ )
13 array[ counter ] = 2 + 2 * counter;
14
15 System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings
uses the modifier final to declare the constant 16
variable Array_Length, whose value is 10. 17 // output each array element's value
18 for ( int counter = 0; counter < array.length; counter++ )

 Common programming error: Assigning 19


20
System.out.printf( "%5d%8d\n", counter, array[ counter ] );
} // end main
a value to a constant after the variable 21 } // end class InitArray
has been initialized is a compilation
Index Value
error. 0 2
1 4
2 6
3 8
4 10
5 12
6 14
7 16
8 18
9 20

02/05/2019 DIANA HAIDAR 9


Examples using Arrays
1 // Fig. 7.5: SumArray.java
4. Summing the Elements of an Array
2 // Computing the sum of the elements of an array.

 The elements of an array represents a 3


4 public class SumArray
series of values to be used in a
5 {
calculation. 6 public static void main( String args[] )
7 {
 The application sums the values 8 int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
contained in an array. 9 int total = 0;
10
11 // add each element's value to total
12 for ( int counter = 0; counter < array.length; counter++ )
13 total += array[ counter ];
14
15 System.out.printf( "Total of array elements: %d\n", total );
16 } // end main
17 } // end class SumArray
Total of array elements: 849

02/05/2019 DIANA HAIDAR 10


Examples using Arrays
5. Using Bar Charts to Display Array Data
Graphically
 Presents data to users in a graphical manner.
 Example: numeric values are often displayed
as bars in a bar chart.

The 0 flag in the format specifier indicates that values


with fewer digits than the field width (2) should begin
with a leading 0.

02/05/2019 DIANA HAIDAR 11


1 // Fig. 7.7: RollDie.java

Examples using Arrays 2


3
// Roll a six-sided die 6000 times.
import java.util.Random;
4
6. Using the Elements of an Array as 5 public class RollDie
6 {
Counters
7 public static void main( String args[] )
{
 Uses counter variables to summarize 8
9 Random randomNumbers = new Random(); // random number generator
data. 10 int frequency[] = new int[ 7 ]; // array of frequency counters
 Example: using separate counters in 11
a die-rolling program to track the 12 // roll die 6000 times; use die value as frequency index
13 for ( int roll = 1; roll <= 6000; roll++ )
number of occurrences of each side
14 ++frequency[ 1 + randomNumbers.nextInt( 6 ) ];
of a die as the program rolled the 15
die 6000 times. 16 System.out.printf( "%s%10s\n", "Face", "Frequency" );
17
18 // output each array element's value
19 for ( int face = 1; face < frequency.length; face++ )
20 System.out.printf( "%4d%10d\n", face, frequency[ face ] );
21 } // end main
22 } // end class RollDie

Face Frequency
1 988
2 963
3 1018
4 1041
5 978
6 1012

02/05/2019 DIANA HAIDAR 12


Examples using Arrays 1 // Fig. 7.8: StudentPoll.java
2 // Poll analysis program.
3
7. Using Arrays to Analyze Survey
4 public class StudentPoll
Results 5 {
6 public static void main( String args[] )
 Uses arrays to summarize the 7 {
results of data collected in a 8 // array of survey responses
survey. 9 int responses[] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6,
 Example: Summarize the 10 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6,
number of responses of each 11 4, 8, 6, 8, 10 };

type (1 to 10). 12 int frequency[] = new int[ 11 ]; // array of frequency counters


13
14 // for each answer, select responses element and use that value
15 // as frequency index to determine element to increment
16 for ( int answer = 0; answer < responses.length; answer++ )
17 ++frequency[ responses[ answer ] ];
18
19 System.out.printf( "%s%10s", "Rating", "Frequency" );
20
21 // output each array element's value
22 for ( int rating = 1; rating < frequency.length; rating++ )
23 System.out.printf( "%d%10d", rating, frequency[ rating ] );
24 } // end main
25 } // end class StudentPoll

02/05/2019 DIANA HAIDAR 13


Enhanced for Statement
 The enhanced for statement iterates through the elements of an array or a collection without using a
counter.
 The syntax of an enhanced for statement is:

where arrayName is the array through which to iterate, and parameter has two parts:
 a type (e.g. int) which must match the type of the elements in the array; and
 an identifier which represents the successive values in the array on successive iterations.
 The enhanced for header can be read concisely as "for each iteration, assign the next element of
arrayName to parameter, then execute the following statement".
 The enhanced for statement can be used only to access array elements, however, it cannot be used to
modify elements or to access the index number of each array element.
 If the latter, use the traditional counter-controlled for statement.

02/05/2019 DIANA HAIDAR 14


Enhanced for Statement
 The enhanced for statement iterates 1 // Fig. 7.12: EnhancedForTest.java
2 // Using enhanced for statement to total integers in an array.
through the successive values in the 3
array one-by-one. 4 public class EnhancedForTest
5 {
6 public static void main( String args[] )
7 {
8 int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
9 int total = 0;
10
11 // add each element's value to total
12 for ( int number : array )
13 total += number;
14
15 System.out.printf( "Total of array elements: %d\n", total );
16 } // end main
17 } // end class EnhancedForTest

Total of array elements: 849

02/05/2019 DIANA HAIDAR 15


Passing Arrays to Methods
1 // Fig. 7.13: PassArray.java

 To pass an array argument to a method, 2


3
// Passing arrays and individual array elements to methods.

specify the name of the array without any 4 public class PassArray
brackets. 5 {
6 // main creates array and calls modifyArray and modifyElement
7 public static void main( String args[] )
8 {
 Every array object knows its own length 9 int array[] = { 1, 2, 3, 4, 5 };
(via length field), thus, we need not pass 10
11 System.out.println(
the array length as an additional 12 "Effects of passing reference to entire array:\n" +
argument into a method. 13 "The values of the original array are:" );
14
When an argument to a method is an 15 // output original array elements
entire array or an individual array element 16 for ( int value : array )
of a reference type, the called method 17 System.out.printf( " %d", value );
18
receives a copy of the reference. 19 modifyArray( array ); // pass array reference
 Modifying a reference type in the 20 System.out.println( "\n\nThe values of the modified array are:" );
called method modifies the original 21
22 // output modified array elements
value of that reference.
23 for ( int value : array )
24 System.out.printf( " %d", value );
25
26 System.out.printf(
27 "\n\nEffects of passing array element value:\n" +
28 "array[3] before modifyElement: %d\n", array[ 3 ] );
02/05/2019 DIANA HAIDAR 16
Passing Arrays to Methods 29
30 modifyElement( array[ 3 ] ); // attempt to modify array[ 3 ]
31 System.out.printf(
 When an argument to a method is an 32 "array[3] after modifyElement: %d\n", array[ 3 ] );
individual array element of a primitive 33 } // end main
type, the called method receives a copy 34
35 // multiply each element of an array by 2
of the element's value. 36 public static void modifyArray( int array2[] )
 Modifying the copy of the element's 37 {
value in the called method does not 38 for ( int counter = 0; counter < array2.length; counter++ )
39 array2[ counter ] *= 2;
affect the original value of that 40 } // end method modifyArray
element. 41
42 // multiply argument by 2
43 public static void modifyElement( int element )
44 {
45 element *= 2;
46 System.out.printf(
 For a method to receive an array 47 "Value of element in modifyElement: %d\n", element );
reference through a method call, the 48 } // end method modifyElement
method's parameter list must specify an 49 } // end class PassArray

array parameter. Effects of passing reference to entire array:


The values of the original array are:
1 2 3 4 5

The values of the modified array are:


2 4 6 8 10

Effects of passing array element value:


array[3] before modifyElement: 8
Value of element in modifyElement: 16
array[3] after modifyElement: 8

02/05/2019 DIANA HAIDAR 17


Case Study: Class GradeBook using an Array to Store Grades
1 // Fig. 7.14: GradeBook.java

 This version of class GradeBook uses an 2 // Grade book using an array to store test grades.
3
array of integers to store the grades of 4 public class GradeBook
several students on a single exam. 5 {
6 private String courseName; // name of course this GradeBook represents
 This eliminates the need to repeatedly 7 private int grades[]; // array of student grades
input the same set of grades. 8
9 // two-argument constructor initializes courseName and grades array
10 public GradeBook( String name, int gradesArray[] )
11 {
12 courseName = name; // initialize courseName
13 grades = gradesArray; // store grades
14 } // end two-argument GradeBook constructor
15
16 // method to set the course name
17 public void setCourseName( String name )
18 {
19 courseName = name; // store the course name
20 } // end method setCourseName
21
22 // method to retrieve the course name
23 public String getCourseName()
24 {
25 return courseName;
26 } // end method getCourseName
27
02/05/2019 DIANA HAIDAR 18
Case Study: Class GradeBook using an Array to Store Grades
28 // display a welcome message to the GradeBook user
29 public void displayMessage()
30 {
31 // getCourseName gets the name of the course
32 System.out.printf( "Welcome to the grade book for\n%s!\n\n",
33 getCourseName() );
34 } // end method displayMessage
35
36 // perform various operations on the data
37 public void processGrades()
38 {
39 // output grades array
40 outputGrades();
41
42 // call method getAverage to calculate the average grade
43 System.out.printf( "\nClass average is %.2f\n", getAverage() );
44
45 // call methods getMinimum and getMaximum
46 System.out.printf( "Lowest grade is %d\nHighest grade is %d\n\n",
47 getMinimum(), getMaximum() );
48
49 // call outputBarChart to print grade distribution chart
50 outputBarChart();
51 } // end method processGrades
52
53 // find minimum grade
54 public int getMinimum()
55 {
56 int lowGrade = grades[ 0 ]; // assume grades[ 0 ] is smallest
57
02/05/2019 DIANA HAIDAR 19
Case Study: Class GradeBook using an Array to Store Grades
85 // determine average grade for test
86 public double getAverage()
87 {
88 int total = 0; // initialize total
89
90 // sum grades for one student
91 for ( int grade : grades )
92 total += grade;
93
94 // return average of grades
95 return (double) total / grades.length;
96 } // end method getAverage
97
98 // output bar chart displaying grade distribution
99 public void outputBarChart()
100 {
101 System.out.println( "Grade distribution:" );
102
103 // stores frequency of grades in each range of 10 grades
104 int frequency[] = new int[ 11 ];
105
106 // for each grade, increment the appropriate frequency
107 for ( int grade : grades )
108 ++frequency[ grade / 10 ];
109

02/05/2019 DIANA HAIDAR 20


Case Study: Class GradeBook using an Array to Store Grades
1 // Fig. 7.15: GradeBookTest.java
2 // Creates GradeBook object using an array of grades.
3
4 public class GradeBookTest
5 {
6 // main method begins program execution
7 public static void main( String args[] )
8 {
9 // array of student grades
10 int gradesArray[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
11
12 GradeBook myGradeBook = new GradeBook(
13 "CS101 Introduction to Java Programming", gradesArray );
14 myGradeBook.displayMessage();
15 myGradeBook.processGrades();
16 } // end main
17 } // end class GradeBookTest

02/05/2019 DIANA HAIDAR 21


Multidimensional Arrays
 Multidimensional arrays with two dimensions – two dimensional arrays -- are often used to represent
tables of values consisting of information arranged in rows and columns.
 To identify a particular element, we must specify two indices: the first identifies the element's row, and
the second its column.
 An array with m rows and n columns is called an m-by-n array.

02/05/2019 DIANA HAIDAR 22


Multidimensional Arrays
Arrays of One-Dimensional Arrays
 Multi-dimensional arrays can be initialized with array initializers in declarations.
 Example: A two-dimensional array b with 3 rows and 2 columns could be declared and initialized with
nested array initializers as follows:

 The compiler counts the number of nested array initializers (represented by set of braces within the outer
braces) in array declaration to determine the number of rows in array.

 A multi-dimensional array with the same number of columns in every row can be created with an array-
creation expression.

02/05/2019 DIANA HAIDAR 23


Multidimensional Arrays
Two-Dimensional Arrays with Rows of Different Lengths
 The lengths of the rows of array are not required to be the same.
 Example:

A multi-dimensional array in which each row has a different number of columns can be created as follows:

02/05/2019 DIANA HAIDAR 24


Multidimensional Arrays
1 // Fig. 7.17: InitArray.java 19 // output rows and columns of a two-dimensional array
2 // Initializing two-dimensional arrays. 20 public static void outputArray( int array[][] )
3 21 {
4 public class InitArray 22 // loop through array's rows
5 { 23 for ( int row = 0; row < array.length; row++ )
6 // create and output two-dimensional arrays 24 {
7 public static void main( String args[] ) 25 // loop through columns of current row
8 { 26 for ( int column = 0; column < array[ row ].length; column++ )
9 int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } }; 27 System.out.printf( "%d ", array[ row ][ column ] );
10 int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } }; 28
11 29 System.out.println(); // start new line of output
12 System.out.println( "Values in array1 by row are" ); 30 } // end outer for
13 outputArray( array1 ); // displays array1 by row 31 } // end method outputArray
14 32 } // end class InitArray
15 System.out.println( "\nValues in array2 by row are" );
Values in array1 by row are
16 outputArray( array2 ); // displays array2 by row 1 2 3
17 } // end main 4 5 6
18 Values in array2 by row are
1 2
3
4 5 6

02/05/2019 DIANA HAIDAR 25


Multidimensional Arrays
Common Multi-Dimensional Array Manipulations Performed with for Statements
 Many common array manipulations use:
 for statement:

 Or nested for statement

02/05/2019 DIANA HAIDAR 26


Case Study: class GradeBook using a Two-Dimensional Array
1 // Fig. 7.18: GradeBook.java
2 // Grade book using a two-dimensional array to store grades.
3
4 public class GradeBook
5 {
6 private String courseName; // name of course this grade book represents
7 private int grades[][]; // two-dimensional array of student grades
8
9 // two-argument constructor initializes courseName and grades array
10 public GradeBook( String name, int gradesArray[][] )
11 {
12 courseName = name; // initialize courseName
13 grades = gradesArray; // store grades
14 } // end two-argument GradeBook constructor
15
16 // method to set the course name
17 public void setCourseName( String name )
18 {
19 courseName = name; // store the course name
20 } // end method setCourseName
21
22 // method to retrieve the course name
23 public String getCourseName()
24 {
25 return courseName;
26 } // end method getCourseName
27
02/05/2019 DIANA HAIDAR 27
Case Study: class GradeBook using a Two-Dimensional Array
28 // display a welcome message to the GradeBook user
29 public void displayMessage()
30 {
31 // getCourseName gets the name of the course
32 System.out.printf( "Welcome to the grade book for\n%s!\n\n",
33 getCourseName() );
34 } // end method displayMessage
35
36 // perform various operations on the data
37 public void processGrades()
38 {
39 // output grades array
40 outputGrades();
41
42 // call methods getMinimum and getMaximum
43 System.out.printf( "\n%s %d\n%s %d\n\n",
44 "Lowest grade in the grade book is", getMinimum(),
45 "Highest grade in the grade book is", getMaximum() );
46
47 // output grade distribution chart of all grades on all tests
48 outputBarChart();
49 } // end method processGrades
50
51 // find minimum grade
52 public int getMinimum()
53 {
54 // assume first element of grades array is smallest
55 int lowGrade = grades[ 0 ][ 0 ];
56
02/05/2019 DIANA HAIDAR 28
Case Study: class GradeBook using a Two-Dimensional Array
57 // loop through rows of grades array
58 for ( int studentGrades[] : grades )
59 {
60 // loop through columns of current row
61 for ( int grade : studentGrades )
62 {
63 // if grade less than lowGrade, assign it to lowGrade
64 if ( grade < lowGrade )
65 lowGrade = grade;
66 } // end inner for
67 } // end outer for
68
69 return lowGrade; // return lowest grade
70 } // end method getMinimum
71
72 // find maximum grade
73 public int getMaximum()
74 {
75 // assume first element of grades array is largest
76 int highGrade = grades[ 0 ][ 0 ];
77

02/05/2019 DIANA HAIDAR 29


Case Study: class GradeBook using a Two-Dimensional Array
78 // loop through rows of grades array
79 for ( int studentGrades[] : grades )
80 {
81 // loop through columns of current row
82 for ( int grade : studentGrades )
83 {
84 // if grade greater than highGrade, assign it to highGrade
85 if ( grade > highGrade )
86 highGrade = grade;
87 } // end inner for
88 } // end outer for
89
90 return highGrade; // return highest grade
91 } // end method getMaximum
92
93 // determine average grade for particular set of grades
94 public double getAverage( int setOfGrades[] )
95 {
96 int total = 0; // initialize total
97
98 // sum grades for one student
99 for ( int grade : setOfGrades )
100 total += grade;
101
102 // return average of grades
103 return (double) total / setOfGrades.length;
104 } // end method getAverage
105
02/05/2019 DIANA HAIDAR 30
Case Study: class GradeBook using a Two-Dimensional Array
106 // output bar chart displaying overall grade distribution
107 public void outputBarChart()
108 {
109 System.out.println( "Overall grade distribution:" );
110
111 // stores frequency of grades in each range of 10 grades
112 int frequency[] = new int[ 11 ];
113
114 // for each grade in GradeBook, increment the appropriate frequency
115 for ( int studentGrades[] : grades )
116 {
117 for ( int grade : studentGrades )
118 ++frequency[ grade / 10 ];
119 } // end outer for
120
121 // for each grade frequency, print bar in chart
122 for ( int count = 0; count < frequency.length; count++ )
123 {
124 // output bar label ( "00-09: ", ..., "90-99: ", "100: " )
125 if ( count == 10 )
126 System.out.printf( "%5d: ", 100 );
127 else
128 System.out.printf( "%02d-%02d: ",
129 count * 10, count * 10 + 9 );
130
131 // print bar of asterisks
132 for ( int stars = 0; stars < frequency[ count ]; stars++ )
133 System.out.print( "*" );

02/05/2019 DIANA HAIDAR 31


Case Study: class GradeBook using a Two-Dimensional Array
134
135 System.out.println(); // start a new line of output
136 } // end outer for
137 } // end method outputBarChart
138
139 // output the contents of the grades array
140 public void outputGrades()
141 {
142 System.out.println( "The grades are:\n" );
143 System.out.print( " " ); // align column heads
144
145 // create a column heading for each of the tests
146 for ( int test = 0; test < grades[ 0 ].length; test++ )
147 System.out.printf( "Test %d ", test + 1 );
148
149 System.out.println( "Average" ); // student average column heading
150
151 // create rows/columns of text representing array grades
152 for ( int student = 0; student < grades.length; student++ )
153 {
154 System.out.printf( "Student %2d", student + 1 );
155
156 for ( int test : grades[ student ] ) // output student's grades
157 System.out.printf( "%8d", test );
158

02/05/2019 DIANA HAIDAR 32


Case Study: class GradeBook using a Two-Dimensional Array
1 // Fig. 7.19: GradeBookTest.java
2 // Creates GradeBook object using a two-dimensional array of grades.
3
4 public class GradeBookTest
5 {
6 // main method begins program execution
7 public static void main( String args[] )
8 {
9 // two-dimensional array of student grades
10 int gradesArray[][] = { { 87, 96, 70 },
11 { 68, 87, 90 },
12 { 94, 100, 90 },
13 { 100, 81, 82 },
14 { 83, 65, 85 },
15 { 78, 87, 65 },
16 { 85, 75, 83 },
17 { 91, 94, 100 },
18 { 76, 72, 84 },
19 { 87, 93, 73 } };
20
21 GradeBook myGradeBook = new GradeBook(
22 "CS101 Introduction to Java Programming", gradesArray );
23 myGradeBook.displayMessage();
24 myGradeBook.processGrades();
25 } // end main
26 } // end class GradeBookTest

02/05/2019 DIANA HAIDAR 33


Case Study: class GradeBook using a Two-Dimensional Array
Welcome to the grade book for
CS101 Introduction to Java Programming!

The grades are:

Test 1 Test 2 Test 3 Average


Student 1 87 96 70 84.33
Student 2 68 87 90 81.67
Student 3 94 100 90 94.67
Student 4 100 81 82 87.67
Student 5 83 65 85 77.67
Student 6 78 87 65 76.67
Student 7 85 75 83 81.00
Student 8 91 94 100 95.00
Student 9 76 72 84 77.33
Student 10 87 93 73 84.33

Lowest grade in the grade book is 65


Highest grade in the grade book is 100

Overall grade distribution:


00-09:
10-19:
20-29:

30-39:
40-49:
50-59:
60-69: ***
70-79: ******
80-89: ***********
90-99: *******
100: ***

02/05/2019 DIANA HAIDAR 34


Variable-Length Arguments Lists
 Programmers can create methods that receive an unspecified number of arguments.
 An argument type followed by an ellipsis (…) in a method’s parameter list indicates that the method
receives variable number of arguments of that particular type.

 Common programming error: Placing an ellipsis in the middle of a method parameter list is a syntax error.
An ellipsis may be placed only at the end of the parameter list.

02/05/2019 DIANA HAIDAR 35


Variable-Length Arguments Lists
1 // Fig. 7.20: VarargsTest.java 25 System.out.printf( "d1 = %.1f\nd2 = %.1f\nd3 = %.1f\nd4 = %.1f\n\n",
2 // Using variable-length argument lists. 26 d1, d2, d3, d4 );
3 27
4 public class VarargsTest 28 System.out.printf( "Average of d1 and d2 is %.1f\n",
5 {
29 average( d1, d2 ) );
6 // calculate average
30 System.out.printf( "Average of d1, d2 and d3 is %.1f\n",
7 public static double average( double... numbers )
31 average( d1, d2, d3 ) );
8 {
32 System.out.printf( "Average of d1, d2, d3 and d4 is %.1f\n",
9 double total = 0.0; // initialize total
10 33 average( d1, d2, d3, d4 ) );
11 // calculate total using the enhanced for statement 34 } // end main
12 for ( double d : numbers ) 35 } // end class VarargsTest
13 total += d;
d1 = 10.0
14 d2 = 20.0
15 return total / numbers.length; d3 = 30.0
d4 = 40.0
16 } // end method average
17 Average of d1 and d2 is 15.0
18 public static void main( String args[] ) Average of d1, d2 and d3 is 20.0
Average of d1, d2, d3 and d4 is 25.0
19 {
20 double d1 = 10.0;
21 double d2 = 20.0;
22 double d3 = 30.0;
23 double d4 = 40.0;
24

02/05/2019 DIANA HAIDAR 36


Using Command-Line Arguments
 On many systems, it is possible to pass arguments from the command line (these are known as command-
line arguments) to an application by including a parameter String[ ] in the parameter list of main.
 Java passes the command-line arguments that appear after the class name in the java command to the
application’s main method as Strings in the array args.
 String[ ] args
 Java MyClass a b
 args[0] contains String a, and args[1] contains String b
 The command-line arguments are separated by white space, not commas.
 The number of arguments passed in from the command-line is obtained by accessing the array’s length
attribute.
 args.length

02/05/2019 DIANA HAIDAR 37


Using Command-Line Arguments
1 // Fig. 7.21: InitArray.java
2 // Using command-line arguments to initialize an array.
3
4 public class InitArray
5 {
6 public static void main( String args[] )
7 {
8 // check number of command-line arguments
9 if ( args.length != 3 )
10 System.out.println(
11 "Error: Please re-enter the entire command, including\n" +
12 "an array size, initial value and increment." );
13 else
14 {
15 // get array size from first command-line argument
16 int arrayLength = Integer.parseInt( args[ 0 ] );
17 int array[] = new int[ arrayLength ]; // create array
18
19 // get initial value and increment from command-line argument
20 int initialValue = Integer.parseInt( args[ 1 ] );
21 int increment = Integer.parseInt( args[ 2 ] );
22
23 // calculate value for each array element
24 for ( int counter = 0; counter < array.length; counter++ )
25 array[ counter ] = initialValue + increment * counter;
26
27 System.out.printf( "%s%8s\n", "Index", "Value" );
28

02/05/2019 DIANA HAIDAR 38

You might also like