Presentation is loading. Please wait.

Presentation is loading. Please wait.

More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226.

Similar presentations


Presentation on theme: "More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226."— Presentation transcript:

1 More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226

2 More from Chapters 5 thru 7 n More on Arrays  create and manipulate arrays of objects  multi-dimensional arrays n More on Methods and Constructors  understand overloading  create and use overloaded methods  create and use overloaded constructors

3 Using Arrays with Classes n Each student has several grades  array as an instance variable of Student  we added a list of assignments  only some assignments graded so far n Several students in a course  array of Student objects n Make a grade sheet program  list of Students, each with grades Student.java ClassList.java GradeSheet.java

4 Array Instance Variables n Declare array instance variable private private int[] asgnGrades; n 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; n Create the array object in the constructor asgnGrades = new int[NUM_ASGN];

5 Array Getters and Setters n Protect our data from their grubby paws!  getter returns a copy of the array public int[] getAsgnGrades() { return Arrays.copyOf(asgnGrades, asgnsGraded); return Arrays.copyOf(asgnGrades, asgnsGraded);}  setter copies values OR saves a copy public void setAsgnGrades(int[] newGrades) { if (areValidGrades(newGrades)) { if (areValidGrades(newGrades)) { asgnGrades = Arrays.copyOf(newGrades, NUM_ASGN); asgnGrades = Arrays.copyOf(newGrades, NUM_ASGN); }}

6 Arrays Class n We’ve seen Arrays before: Arrays.toString  has some useful methods for arrays »copyOf, equals, fill, sort, and others n copyOf method copies the array  tell it how big the new array should be  getter: array should only be graded assignments return Arrays.copyOf(asgnGrades, asgnsGraded);  setter: array needs space for all assignments asgnGrades = Arrays.copyOf(newGrades, NUM_ASGN);

7 Partly Full Array n Eight assignments, but only two graded!  NUM_ASGN == 8; asgnsGraded == 2 n (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) {... }

8 Exercise n Create an array for up to 100 numbers (int)  create a constant for the maximum n Ask user for how many numbers they have  assume they give a good # n Read that many numbers into the array

9 Arrays of Objects n Generally have many students at once  lots of objects of same type  treated the same  an array! n Arrays of objects a little bit more complicated than arrays of primitives  but not much!

10 Creating an Array of Students n Create the Student array variable and object Student[] student = new Student[MAX];  Student[] student creates the array variable  new Student[MAX] creates the array object n Do we now have MAX Student objects?  NO! We just have that many Student variables n An array is a collection of variables  each variable needs to have a Student object created for it! ClassList.java

11 Creating an Array of Students n Loop reads a name, creates a Student for (int s = 0; s < student.length; s++) { S.o.p(“Enter Student’s name: ”); S.o.p(“Enter Student’s name: ”); String name = kbd.nextLine(); String name = kbd.nextLine(); student[s] = new Student(name); 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

12 Arrays of Objects n Create the array… n …then the array elements / / / / / / student A00000001 “Alice” STUDENT_NUMBER studentName & A00000002 “Bill” STUDENT_NUMBER studentName & A00000003 “Carole” STUDENT_NUMBER studentName &

13 Printing Class List n Now we have all the objects created, we can just use them as usual for (int s = 0; s < student.length; s++) { S.o.pln(student[s].getANumber() + “ ” S.o.pln(student[s].getANumber() + “ ” + student[s].getName()); + student[s].getName());}  student[s] is a Student »getANumber() the student's # in A00000000 format »getName() the student's name ClassList.java

14 Exercise n Create an array of ten Thingamajigs, sized from 1 to 10  Note: new Thingamajig(n) creates a Thingamajig of size n n Write a loop to add up the sizes of the Thingamajig in the array  use the getSize() method!

15 Assigning Grades to a Student n Client assigns grades to a student  create student object Student stu = new Student(“Student, Lowell E.”);  assign grades stu.setAsgnGrade(1, 95); stu.setAsgnGrade(2, 100); stu.setAsgnGrade(3, 72); … stu.setAsgnGrade(6, 90);

16 Reading One Student’s Grades n Client can set grade for student for (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

17 Reading Many Students’ Grades n Enter grades for each assignment  for each assignment, read each student’s grade for (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

18 Calculating the Class Average n Add up averages of all students  ask each student for their average n Divide by number of students int sum = 0; for (int s = 0; s < numStu; s++) { sum += student[s].getPctGrade(); } double avg = (double)sum / (double)numStu; GradeSheet.java

19 Exercise n 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 n Write the code

20 Base Types of Arrays n Base type of an array can be anything  declare by adding [] after base type String[] word; n Base type of an array can even be an array!  declare by adding [] after base type! (SAME) int[][] matrix; n Create by specifying both dimensions double[][] sales = new double[ROWS][COLS];

21 Picturing Arrays of Arrays n Normal way of drawing arrays & matrices  arr is an int[]  mat is an int[][] 0 0 0 0 0 0 0 0 arr 0 0 0 0 0 0 0 0 mat 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 A matrix is an array of arrays where every row is the same length. One matrix; two matrices.

22 Extracting from Arrays of Arrays n Normal way of drawing arrays & matrices  arr is an int[]arr[3] is an int  mat is an int[][]mat[5] is an int[] 0 0 0 0 0 0 0 0 arr 0 0 0 0 0 0 0 0 mat 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 arr[3] mat[5]

23 Extracting from Matrices n 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 0 0 0 0 0 0 0 0 mat 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 mat[5] mat[5][2]

24 Matrix Elements n Can think of it as a table  first say what row you want,  then what column 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 mat[5][2] = 7; 0 123 0 1 2 3 4 5 6 7 7

25 Declaration Exercises n 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

26 Processing a Matrix n Usually nested loops n Usually row by row for (int row=0; row<numRows; row++) for (int col=0; col<numCols; col++) for (int col=0; col<numCols; col++)...a[row][col]......a[row][col]... n Sometimes column by column for (int col=0; col<numCols; col++) for (int row=0; row<numRows; row++) for (int row=0; row<numRows; row++)...a[row][col]......a[row][col]... But rows always come first when selecting from the array

27 It’s Called Row Processing... n Because you’re doing one row at a time  for each row, do each column in that row 0 1 2 3 4 5 0 1 2 3 4 5 0 3 5 2 9 8 8 1 5 5 4 6 7 4 2 2 3 5 3 5 4 3 4 4 7 9 2 1 4 3 2 3 8 8 5 Total 31 35 22 27 29

28 Likewise Column Processing... n Processes one column at a time  for each column, do each row in that column 0 1 2 3 4 5 0 1 2 3 4 5 0 3 5 2 9 8 8 1 5 5 4 6 7 4 2 2 3 5 3 5 4 3 4 4 7 9 2 1 4 3 2 3 8 8 5 Total 191721353022

29 Exercise n Row processing or column processing?  Calculate annual sales totals  Calculate average sales by month // Up to 25 years of monthly sales public 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 # years int y, m; // yr/month index

30 Annual Sales n Row processing double annualSales;... for (y=0; y<numYrs; y++) { annualSales = 0.0; annualSales = 0.0; for (m=0; m<NUM_MOS; m++) for (m=0; m<NUM_MOS; m++) annualSales += sales[y][m]; annualSales += sales[y][m];......} Years are rows Months are columns

31 Average Sales by Month n Column processing double aveSales;... for (m=0; m<NUM_MOS; m++) { double total = 0.0; double total = 0.0; for (y=0; y<numYrs; y++) for (y=0; y<numYrs; y++) total += sales[y][m]; total += sales[y][m]; aveSales = total / numYrs; aveSales = total / numYrs;......} Years are rows Months are columns

32 Higher Dimensions n 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]; n Pretty rare n 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 :-)

33 Game of Life n Cells on a board  two-dimensional array of cells n Generations pass n Each generation depends on one before it  keep track of previous generation  want two boards – use an array char[][][] board = new char[2][ROWS][COLS];

34 Life Boards n board[0] n board[1]

35 Overloading n Consider println System.out.println(“This is a string”); System.out.println(42);System.out.println(3.14);System.out.println(); n What’s the argument type for println?  String, int, double, nothing?  it’s actually 4 methods with the same name!

36 Picking a Method n Java figures out which method by looking at the arguments in the method call System.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() {... }

37 Overloaded Methods (Stubs) n Need the argument types to be different public void println(String s) {} public void println(int n) {} public void println(double d) {} public void println() {}  can’t repeat the same argument type sequence public void println(String t) {} »not even if the parameter names are different! »Java can’t choose between them

38 Matching Methods n Java looks for an exact match  doThis(10) looks for doThis(int) n If no exact match, looks for a close match  no doThis(int)? look for doThis(double)! n 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)

39 Multiple Parameters n Arguments match parameters in order n OK to have same types in different order doThis(double x, String s) doThis(String s, double x) n Or different numbers of arguments doThis(double x) doThis(String s, double x, String t)  so long as Java can tell them apart!

40 Exercise n Match the method calls to the definitions i.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) {... }

41 Writing Overloaded Methods n Mostly methods with the same name are doing more-or-less the same thing  recall: name says what it does/returns n Try to re-use code  print a title, underlined with ‘-’s printTitle(“My Title”);  print a title, underlined with ‘=’s printTitle(“My Big Title”, “=”);  “default” argument

42 printTitle Code n Old code used hyphen to underline title  change it to use parameter character public static void printTitle(String title, char under) { System.out.println(“\n” + title); System.out.println(“\n” + title); for (int i = 0; i < title.length; ++i) { for (int i = 0; i < title.length; ++i) { System.out.print(under); System.out.print(under); } System.out.println(“\n”); System.out.println(“\n”);} add parameter change ‘-’ to new parameter

43 printTitle Code n For old behaviour: printTitle(“Blah”, ‘-’)  but we want printTitle(“Blah”) like before! n So make another method:  header is the “short” version we want  body is the long version we would have needed public static void printTitle(String title) { printTitle(title, ‘-’); printTitle(title, ‘-’);}

44 “Default Parameters” in Java n 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 parameters public static void printTitle(String title) »they call the method with the most parameters »they “fill in” the missing arguments printTitle(title, ‘-’); printTitle(title, ‘-’); if underline char is missing fill it in with ‘-’

45 Exercise n 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 *)

46 Overloaded Constructors n Same for constructors as for methods  consider Scanner Scanner 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!

47 Default Constructor Arguments n Student constructor has two-arguments Student stu = new Student(“Dent, Stu”, 85);  name and percentage grade n Student grades start off at 0, usually  make it easy to create Student w. pctGrade = 0 Student s = new Student(“Tudiaunt, A.”);  pctGrade not specified, so set it to 0

48 Exercise n Given these constructors a)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) n Which constructor gets called? i)Thing thing1 = new Thing(“Cat”, “Hat”); ii)Thing thing2 = new Thing(“Thing”, 2); iii)Thing thing3 = new Thing();

49 Secondary Constructors n 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)

50 Calling a Constructor n Special way to do it:  use “this” instead of “Student” (class name) public Student(String n) { this(n, 0); 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

51 n = “Chris”, g = 0 n = “Chris” Constructor Calling n Client uses one argument constructor Student s = new Student(“Chris”);  Java starts one-argument constructor public Student(String n) { »n is “Chris” this(n, 0); this(n, 0);  one-argument constructor calls two-argument public Student(String n, pctGrade g) { »n is “Chris”, g is 0 »2-arg constructor does what needs doing

52 Secondary Constructors n 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

53 Exercise n This constructor is defined: public Thing(String a, String b, int c) n 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)

54 Questions


Download ppt "More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226."

Similar presentations


Ads by Google