Date post: | 03-Jan-2016 |
Category: |
Documents |
Upload: | irma-thomas |
View: | 213 times |
Download: | 0 times |
More from Chapters 5 thru 7
More on Arrays create and manipulate arrays of objects multi-dimensional arrays
More on Methods and Constructors understand overloading create and use overloaded methods create and use overloaded constructors
Using Arrays with Classes
Each student has several grades array as an instance variable of Student we added a list of assignments only some assignments graded so far
Several students in a course array of Student objects
Make a grade sheet program list of Students, each with grades
Student.java
ClassList.java
GradeSheet.java
Array Instance Variables
Declare array instance variable privateprivate int[] asgnGrades;
Create extra variables as required size of array (static all objects same size)public static final int NUM_ASGN = 8; used places (static all objects same # used)private static int gradedAsgns = 0;
Create the array object in the constructorasgnGrades = new int[NUM_ASGN];
Array Getters and Setters
Protect our data from their grubby paws! getter returns a copy of the arraypublic int[] getAsgnGrades() { return Arrays.copyOf(asgnGrades, asgnsGraded);} setter copies values OR saves a copypublic void setAsgnGrades(int[] newGrades) { if (areValidGrades(newGrades)) { asgnGrades = Arrays.copyOf(newGrades, NUM_ASGN); }}
Arrays Class
We’ve seen Arrays before: Arrays.toString has some useful methods for arrays
» copyOf, equals, fill, sort, and others
copyOf method copies the array tell it how big the new array should be getter: array should only be graded assignmentsreturn Arrays.copyOf(asgnGrades, asgnsGraded); setter: array needs space for all assignmentsasgnGrades = Arrays.copyOf(newGrades, NUM_ASGN);
Partly Full Array
Eight assignments, but only two graded! NUM_ASGN == 8; asgnsGraded == 2
(Generally) process only the used part loop for full array:for (int i = 0; i < NUM_ASGN; ++i) { ... }
» OR for (int i = 0; i < asgnGrades.length; ++i) { ... }
loop for partly full array:for (int i = 0; i < asgnsGraded; ++i) { ... }
Exercise
Create an array for up to 100 numbers (int) create a constant for the maximum
Ask user for how many numbers they have assume they give a good #
Read that many numbers into the array
Arrays of Objects
Generally have many students at once lots of objects of same type treated the same an array!
Arrays of objects a little bit more complicated than arrays of primitives but not much!
Creating an Array of Students
Create the Student array variable and objectStudent[] student = new Student[MAX];
Student[] student creates the array variable new Student[MAX] creates the array object
Do we now have MAX Student objects? NO! We just have that many Student variables
An array is a collection of variables each variable needs to have a Student object
created for it!ClassList.java
Creating an Array of Students
Loop reads a name, creates a Studentfor (int s = 0; s < student.length; s++) { S.o.p(“Enter Student’s name: ”); String name = kbd.nextLine(); student[s] = new Student(name);}
using “s” because it’s a mnemonic for “student” recall that Student constructor accepts a name,
assigns a student number
ClassList.java
Arrays of Objects
Create the array… …then the array elements
/
/
/
/
/
/
student
A00000001
“Alice”
STUDENT_NUMBER
studentName
&
A00000002
“Bill”
STUDENT_NUMBER
studentName
&
A00000003
STUDENT_NUMBER
&
Printing Class List
Now we have all the objects created, we can just use them as usualfor (int s = 0; s < student.length; s++) { S.o.pln(student[s].getANumber() + “ ” + student[s].getName());}
student[s] is a Student» getANumber() the student's # in A00000000 format» getName() the student's name
ClassList.java
Exercise
Create an array of ten Thingamajigs, sized from 1 to 10 Note: new Thingamajig(n) creates a
Thingamajig of size n Write a loop to add up the sizes of the
Thingamajig in the array use the getSize() method!
Assigning Grades to a Student
Client assigns grades to a student create student objectStudent stu = new Student(“Student, Lowell E.”); assign gradesstu.setAsgnGrade(1, 95);stu.setAsgnGrade(2, 100);stu.setAsgnGrade(3, 72);…stu.setAsgnGrade(6, 90);
Reading One Student’s Grades
Client can set grade for studentfor (a = 1; a <= Student.NUM_ASGN; a++) {
System.out.print("Enter A" + a + " grade: ");int g = kbd.nextInt(); kbd.nextLine();stu.setAsgnGrade(a, g);
} loop: for each assignment
» prompt for and read a grade» set the student’s grade for that assignment
Reading Many Students’ Grades
Enter grades for each assignment for each assignment, read each student’s gradefor (int a = 1; a <= Student.NUM_ASGN; a++) {
System.out.println("Enter A" + a + " grades: ");for (int s = 0; s < numStu; s++) {
System.out.print(student[s].getStudentName() + "> ");
int g = kbd.nextInt(); kbd.nextLine();student[s].setAsgnGrade(a, g);
}} GradeSheet.java
Calculating the Class Average
Add up averages of all students ask each student for their average
Divide by number of studentsint sum = 0;for (int s = 0; s < numStu; s++) {
sum += student[s].getPctGrade();}double avg = (double)sum / (double)numStu;
GradeSheet.java
Exercise
Suppose we have an array of professors and we want to find their average salary array named professors numProfs professors in the array getSalary method returns a prof’s salary
Write the code
Base Types of Arrays
Base type of an array can be anything declare by adding [] after base typeString[] word;
Base type of an array can even be an array! declare by adding [] after base type! (SAME)int[][] matrix;
Create by specifying both dimensionsdouble[][] sales = new double[ROWS][COLS];
Picturing Arrays of Arrays
Normal way of drawing arrays & matrices arr is an int[] mat is an int[][]
00000000
arr
00000000
mat
00000000
00000000
00000000
A matrix is an array of arrays where every row is the same length.
One matrix; two matrices.
Extracting from Arrays of Arrays
Normal way of drawing arrays & matrices arr is an int[] arr[3] is an int mat is an int[][] mat[5] is an int[]
00000000
arr
00000000
mat
00000000
00000000
00000000
arr[3]
mat[5]
Extracting from Matrices
Matrix is like a list of lists mat is an int[][] mat[5] is an int[] mat[5] is an int[] mat[5][2] is an int
00000000
mat
00000000
00000000
00000000mat[5]
mat[5][2]
Matrix Elements
Can think of it as a table first say what row you want, then what column
00000000
00000000
00000000
00000000
mat[5][2] = 7; 0 1 2 301234567
7
Declaration Exercises
Declare matrices for: 30 rows and 10 columns of integers the names of the months in up to 10 languages monthly sales figures for up to 25 years
Processing a Matrix
Usually nested loops Usually row by rowfor (int row=0; row<numRows; row++) for (int col=0; col<numCols; col++) ...a[row][col]...
Sometimes column by columnfor (int col=0; col<numCols; col++) for (int row=0; row<numRows; row++) ...a[row][col]...
But rows always come first when selecting from the array
It’s Called Row Processing...
Because you’re doing one row at a time for each row, do each column in that row
0 1 2 3 4 50 3 5 2 9 8 81 5 5 4 6 7 42 2 3 5 3 5 43 4 4 7 9 2 14 3 2 3 8 8 5
Total
31
35
22
27
29
Likewise Column Processing...
Processes one column at a time for each column, do each row in that column
0 1 2 3 4 50 3 5 2 9 8 81 5 5 4 6 7 42 2 3 5 3 5 43 4 4 7 9 2 14 3 2 3 8 8 5
Total 1917 21 35 30 22
Exercise
Row processing or column processing? Calculate annual sales totals Calculate average sales by month
// Up to 25 years of monthly salespublic static final int MAX_YRS = 25;public static final int NUM_MOS = 12;double[][] sales = new double[MAX_YRS][NUM_MOS];int numYrs = 0; // current # yearsint y, m; // yr/month index
Annual Sales
Row processingdouble annualSales;...for (y=0; y<numYrs; y++) { annualSales = 0.0; for (m=0; m<NUM_MOS; m++) annualSales += sales[y][m]; ...}
Years are rows
Months are columns
Average Sales by Month
Column processingdouble aveSales;...for (m=0; m<NUM_MOS; m++) { double total = 0.0; for (y=0; y<numYrs; y++) total += sales[y][m]; aveSales = total / numYrs; ...}
Years are rows
Months are columns
Higher Dimensions
Can do 3D, 4D, 5D, etc.int[][][] a = new int[600][400][4];int[][][][] b = new int[10][20][30][40];int[][][][][] c = new int[100][366][24][60][60];
Pretty rare Analogous to 2D case
an array to keep one int value for each second in each minute of each hour in each day in each year of a century (not counting leap seconds :-)
Game of Life
Cells on a board two-dimensional array of cells
Generations pass Each generation depends on one before it
keep track of previous generation want two boards – use an arraychar[][][] board = new char[2][ROWS][COLS];
Overloading
Consider printlnSystem.out.println(“This is a string”);System.out.println(42);System.out.println(3.14);System.out.println();
What’s the argument type for println? String, int, double, nothing? it’s actually 4 methods with the same name!
Picking a Method
Java figures out which method by looking at the arguments in the method callSystem.out.println(“This is a string”);public void println(String s) { ... }System.out.println(42);public void println(int n) { ... }System.out.println(3.14);public void println(double d) { ... }System.out.println();public void println() { ... }
Overloaded Methods (Stubs)
Need the argument types to be differentpublic void println(String s) {}public void println(int n) {}public void println(double d) {}public void println() {} can’t repeat the same argument type sequencepublic void println(String t) {}
» not even if the parameter names are different!» Java can’t choose between them
Matching Methods
Java looks for an exact match doThis(10) looks for doThis(int)
If no exact match, looks for a close match no doThis(int)? look for doThis(double)!
Must be able to assign value to variable can assign an int value to a double variable cannot assign double value to int variable
» so doThis(10.5) will not match doThis(int)
Multiple Parameters
Arguments match parameters in order OK to have same types in different order
doThis(double x, String s)doThis(String s, double x)
Or different numbers of argumentsdoThis(double x)doThis(String s, double x, String t) so long as Java can tell them apart!
Exercise
Match the method calls to the definitionsi. doThis(“Alpha”, “Beta”);ii. doThis(“Gamma”);iii. doThis(20.5);iv. doThis(15); available definitions:a) doThis() { ... }b) doThis(double x) { ... }c) doThis(String s) { ... }d) doThis(String s, String t) { ... }
Writing Overloaded Methods
Mostly methods with the same name are doing more-or-less the same thing recall: name says what it does/returns
Try to re-use code print a title, underlined with ‘-’sprintTitle(“My Title”); print a title, underlined with ‘=’sprintTitle(“My Big Title”, “=”); “default” argument
printTitle Code
Old code used hyphen to underline title change it to use parameter characterpublic static void printTitle(String title, char under) { System.out.println(“\n” + title); for (int i = 0; i < title.length; ++i) { System.out.print(under); } System.out.println(“\n”);}
add parameter
change ‘-’ to new parameter
printTitle Code
For old behaviour: printTitle(“Blah”, ‘-’) but we want printTitle(“Blah”) like before!
So make another method: header is the “short” version we want body is the long version we would have neededpublic static void printTitle(String title) { printTitle(title, ‘-’);}
“Default Parameters” in Java
Actually multiple methods! one method has the most parameters
public static void printTitle(String title, char under)» it has the code for completing the task
other methods have less parameterspublic static void printTitle(String title)» they call the method with the most parameters» they “fill in” the missing arguments printTitle(title, ‘-’);
if underline char is missing
fill it in with ‘-’
Exercise
Suppose we have a method that prints a rectangle (of given dimensions) using *s revise it to use any character given by the client add another (overloaded) method to make old
code work (that is, so that any call that doesn’t say what to use will use a *)
Overloaded Constructors
Same for constructors as for methods consider ScannerScanner kbd = new Scanner(System.in);public Scanner(InputStream is) { ... }Scanner line = new Scanner(“10 20 30”);public Scanner(String s) { ... } different arguments to “the” constructor different constructors!
Default Constructor Arguments
Student constructor has two-argumentsStudent stu = new Student(“Dent, Stu”, 85); name and percentage grade
Student grades start off at 0, usually make it easy to create Student w. pctGrade = 0Student s = new Student(“Tudiaunt, A.”); pctGrade not specified, so set it to 0
Exercise
Given these constructorsa) public Thing()b) public Thing(String a, int c)c) public Thing(String a, String b)d) public Thing(String a, String b, int c)
Which constructor gets called?i) Thing thing1 = new Thing(“Cat”, “Hat”);ii) Thing thing2 = new Thing(“Thing”, 2);iii) Thing thing3 = new Thing();
Secondary Constructors
Our original constructor works OK want our new constructors to work just as well could copy and paste code… …but it’s better to call code
» less work to change it later! want to call our first constructor, adding a 0 Student(“Pat”) same as Student(“Pat”, 0)
» so tell Student(String) to call Student(String, int)
Calling a Constructor
Special way to do it: use “this” instead of “Student” (class name)public Student(String n) { this(n, 0);}
» Note: no “new”, either» Note: nor “return”
Note the arguments: String and int» calls Student(String n, int g), with g set to 0
n = “Chris”, g = 0
n = “Chris”
Constructor Calling
Client uses one argument constructorStudent s = new Student(“Chris”); Java starts one-argument constructorpublic Student(String n) {
» n is “Chris”
this(n, 0); one-argument constructor calls two-argumentpublic Student(String n, pctGrade g) {
» n is “Chris”, g is 0» 2-arg constructor does what needs doing
Secondary Constructors
For now: one constructor is the primary constructor
» the one that has arguments for all settable IVs» it does all the work
other constructors just call the primary one» one line: this(…)» fill in a value for each settable IV that’s missing
Exercise
This constructor is defined:public Thing(String a, String b, int c)
Write new constructors:Thing t1 = new Thing(“aVal”, 10);
» same as Thing(“aVal”, “”, 10)Thing t2 = new Thing(“aVal”, “bVal”);
» same as Thing(“aVal”, “bVal”, 0)Thing t3 = new Thing();
» same as Thing(“Undefined”, “”, 0)