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 Methods and Arrays  create and use methods in a program class  understand primitive vs. reference parameters  understand co-reference  use arrays as instance variables  use partly-filled arrays

3 Method Locations n So far we have:  created a class of related static methods  created a class for objects and their data n Can use methods to help us program  “break up” the task into manageable pieces »“top-down programming”  create methods inside the program class public class SecretSanta { … }

4 Make Secret Santa List n Plan:  get a list of everyone giving presents  make the list of everyone getting presents »(it’s the same list at first)  for each person in the list giving presents: »choose someone else from the list getting presents »remove that someone from the list getting presents »print a message saying who this person’s buying for

5 Make Secret Santa List public static void main(String[] args) { // get a list of everyone giving presents // make the list of everyone getting presents // for each person in the list giving presents: // choose someone else from the list getting presents // remove that someone from the list getting presents // print a message saying who this person’s buying for }

6 Make Secret Santa List public static void main(String[] args) { // get a list of everyone giving presents String[] giving = SecretSanta.getGivingList(); // make the list of everyone getting presents // for each person in the list giving presents: // choose someone else from the list getting presents // remove that someone from the list getting presents // print a message saying who this person’s buying for } What’s the return type of getGivingList?

7 Designing Methods n Need to read a list of names  could just write the code here in main  but that would make main big and hard to read  and also require creating variables that we don’t need anywhere else in main  and right now I’m thinking “big picture” »I need this done, but I don’t care (right now) about the details  so create a method to do it for me

8 Static Methods calling Methods n Location of the method is the current class  getGivingList is in SecretSanta SecretSanta.getGivingList() n NOTE: NOT this.getGivingList() String[] giving = this.getGivingList();  main is static – does not belong to an object »there is no “this” in a static method! non-static variable this cannot be referenced from a static context

9 Calling Own-Class Methods n When the method is in the same class, you don’t need to say the class name String[] giving = getGivingList();  caller is static  called method is static, too String[] giving = getGivingList(); String[] giving = getGivingList();…… public String[] getGivingList { …} non-static method getGivingList() cannot be referenced from a static context But NOTE: the actual mistake is HERE! getGivingList should be declared static.

10 Make Secret Santa List public static void main(String[] args) { // get a list of everyone giving presents String[] giving = getGivingList(); // make the list of everyone getting presents // for each person in the list giving presents: // choose someone else from the list getting presents // remove that someone from the list getting presents // print a message saying who this person’s buying for } public static String[] getGivingList() {

11 Make Secret Santa List public static void main(String[] args) { // get a list of everyone giving presents String[] giving = getGivingList(); // make the list of everyone getting presents String[] getting = copyArray(giving); // for each person in the list giving presents: // choose someone else from the list getting presents // remove that someone from the list getting presents // print a message saying who this person’s buying for } What’s the argument type of copyArray?

12 Make Secret Santa List // get a list of everyone giving presents String[] giving = getGivingList(); // make the list of everyone getting presents String[] getting = copyArray(giving); // for each person in the list giving presents: for (int p = 0; p < giving.length; ++p) { // choose someone else from the list getting presents // remove that someone from the list getting presents // print a message saying who this person’s buying for }

13 Make Secret Santa List // for each person in the list giving presents: for (int p = 0; p < giving.length; ++p) { // choose someone else from the list getting presents String name = chooseSomeone(getting, giving[p]); // remove that someone from the list getting presents removeName(getting, name); // print a message saying who this person’s buying for System.out.println(giving[p] + “ buys for ” + name); } What are the tasks of chooseSomeone and removeName? What are their argument types? What are they for?

14 Exercise n Write stubs for the following functions String[] giving = getGivingList(); String[] getting = copyArray(giving); int p = 0; String name = chooseSomeone(getting, giving[p]); removeName(getting, name);  this is exactly what we did before! »we will be reading some data in the methods »recall how to create and return an array!

15 Tasks/Jobs for Methods n Job is whatever the pseudo-code says  you did write pseudo-code, right??? // choose someone else from the list getting presents String name = chooseSomeone(getting, giving[p]); // remove that someone from the list getting presents removeName(getting, name);  write the javadoc to reflect the job and the purpose of the parameters  write the method that way, too!

16 Javadoc for chooseSomeone n Sample javadoc /** * pick a name (not the given one) from a list * pick a name (not the given one) from a list * * @param gettingList list of names to choose from * @param gettingList list of names to choose from * @param givingName name NOT to choose * @param givingName name NOT to choose * @return a name from gettingList that’s * @return a name from gettingList that’s * not equals to givingName. * not equals to givingName. */ */  choose suitable parameter names »can’t use giving[p] as a parameter name!

17 Exercise n Write a javadoc for removeName // remove that someone from the list getting presents removeName(getting, name);

18 Building Your Program n Create pseudo-code n Create main method, with method calls n Create stubs for the methods called n Repeat until your program is complete  run your program to make sure it’s OK »fix any errors you find  implement another method

19 getGivingList public static String[] getGivingList() { // create a scanner // create a scanner // ask for and read how many names there will be // ask for and read how many names there will be // create a String array of the appropriate size // create a String array of the appropriate size // for each element of the array // for each element of the array // read a name into that element of the array // read a name into that element of the array // return the array // return the array // STUB – delete when above is complete: return new String[1]; return new String[1];}

20 removeName public static void removeName(String[] list, String name) { // for each element of the array // for each element of the array for (int i = 0; i <list.length; ++ i) { for (int i = 0; i <list.length; ++ i) { // if that element is equals to name // if that element is equals to name // remove that element // remove that element }} Angela Barack Vladimir David Vladimir Note: we can name the array parameter anything we want. It’s going to be the same list of names that main gave us.

21 Testing for Equality n Check if list element is same as name  use String’s equals method  list element is list[i], and name is name  so: either of these will work: »name.equals(list[i]) »list[i].equals(name)  except what if list[i] has been removed? »if it doesn’t exist you can’t ask it if it’s equals »better use the first version

22 removeName public static void removeName(String[] list, String name) { // for each element of the array // for each element of the array for (int i = 0; i <list.length; ++ i) { for (int i = 0; i <list.length; ++ i) { // if name is equals to that element // if name is equals to that element if (name.equals(list[i])) { if (name.equals(list[i])) { // remove that element // remove that element } }} Angela Barack Vladimir David Vladimir

23 Removing an Element n Want to remove the name  can’t remove the variable (it’s part of the array)  have to remove the value  need a value that means “there’s nothing here”  that value is null »null can be used with any class type String s = null; Scanner kbd = null; Student stu = null; s kbd stu

24 removeName public static void removeName(String[] list, String name) { // for each element of the array // for each element of the array for (int i = 0; i <list.length; ++ i) { for (int i = 0; i <list.length; ++ i) { // if name is equals to that element // if name is equals to that element if (name.equals(list[i])) { if (name.equals(list[i])) { // remove that element // remove that element list[i] = null; list[i] = null; } }} Angela Barack Vladimir David Vladimir

25 What if We Asked list[i]? n Suppose we had used list[i].equals(name)  after list[i] set to null, there’s no String there  when program runs, it crashes  NullPointerException: asked no one a question  shows names of methods and lines they were on Bill buys for Ben Betty buys for Beryl Exception in thread "main" java.lang.NullPointerException at SecretSanta.removeName(SecretSanta.java:38) at SecretSanta.main(SecretSanta.java:18) Java Result: 1

26 Checking for null n It’s the variable that’s null, not the object  name.equals(null) won’t work »it’s asking the object (that doesn’t exist!) if it’s null  name == null is what you need »it’s checking the variable n You can check for null before you ask if (name != null && name.equals(item[i])) »if name’s not missing and equals to item[i] if (item[i] == null || item[i].equals(name)) »if item[i] is missing or equals to name

27 Arrays vs. Array Variables n Recall we used two different names for the array of people getting gifts  main calls it getting  removeName calls it list n Two different variables… n …but the same array!  array variables “refer to” arrays n When list changes, getting changes (reference) getting (reference) list Angela Barack Vladimir David

28 Change the Array, not the Variable n Can’t make a new array with less elements! »(planning to copy names in)  well you can, but your program won’t work!  list changes… String[] oldList = list; list = new String[list.length -1];  but getting stays the same! (reference) getting (reference) list Angela Barack Vladimir David Angela Barack David (reference) oldList

29 Assignment, Variables, Objects n Assignment changes the variable… n …not the object n Array is a collection of variables, so…  arr[i] = … changes one of arr’s elements  arr = … changes which array arr refers to »the array arr used to refer to is gone unless you have another variable referring to itunless you have another variable referring to it »lost objects are “garbage collected” Java scoops them up & re-uses the memoryJava scoops them up & re-uses the memory

30 Reference vs. Primitive n Primitive data types aren’t reference types  int, double, boolean, … (the small letter types)  each primitive variable holds its own value  primitive parameter has a copy of the argument doThis(h, w); public static void doThis(int hgt, double wid) 40 h 7.3 w 40 hgt 7.3 wid There is no way for doThis to change h or w’s values.

31 Co-Reference n When two variables point to the same array n Or when they point to the same object  objects work the same way as arrays n Variables can be in the same method Car myCar = new Car(); Car stevesCar = new Car(); Car disCar = myCar; (reference) myCar (reference) stevesCar (reference) disCar

32 Co-Reference n Can use either variable to refer to the object n It’s just one object  so if I do this… myCar.setColor(Color.BLUE);  …what color is disCar? (reference) myCar (reference) stevesCar (reference) disCar

33 Important Note n References to arrays and objects can be used to change them  to change an array/object you only need to know where it is  array/object variable keeps track of where it is n Primitive variables don’t get references  to change a primitive variable, you need the variable itself

34 Exercise n What it the output of the following code  assume that sumArray does what it says int[] first = new int[]{10, 20, 30}; int[] second = first; second[0] = 1000; System.out.println(ArrayOperations.sumArray(first)); Recall that new int[]{10, 20, 30}; creates a new array with those three numbers in it. 10 20 30 first

35 Arrays as Instance Variables n Change our Student class so that it has an array of grades rather than a single grade  grades in 8 assignments, say stu A_NUMBER name asgnGrades A00123456 “Dent, Stu” 817510098 869496100

36 Array IV, Getter, and Setter (*) n Just do things normally? private int[] asgnGrades; public int[] getAsgnGrades() { return asgnGrades; return asgnGrades;} public void setAsgnGrades(int[] newGrades) { if (areValidGrades(newGrades)) { // add this method if (areValidGrades(newGrades)) { // add this method asgnGrades = newGrades; asgnGrades = newGrades; }} (*) This is not the best way to do things!

37 Co-Reference Problems n Getter returns the assignment grades array  client can change grades to whatever! int[] stealGrades = stu.getAsgnGrades(); stealGrades[0] = -99;  we’re no longer protecting our information stu A_NUMBER name asgnGrades A00123456 “Dent, Stu” 817510098 869496100 (reference) -99 (reference) stealGrades

38 Return Copies of Arrays n To protect array contents, return a copy public int[] getAsgnGrades() { int[] copy = new int[asgnGrades.length]; int[] copy = new int[asgnGrades.length]; for (int i = 0; i < asgnGrades.length; ++i) { for (int i = 0; i < asgnGrades.length; ++i) { copy[i] = asgnGrades[i]; copy[i] = asgnGrades[i]; } return copy; return copy;} stu A_NUMBER name asgnGrades A00123456 “Dent, Stu” 817510098 869496100 (reference) stealGrades 81 -99 7510098 869496100

39 Another Co-Reference Problem n Setter changes our array to refer to one the client owns – and can modify at will! int[] stealGrades = new int[]{81,75,100,98,86,94,96,100}; stu.setAsgnGrades(stealGrades); stealGrades[0] = -99; stu A_NUMBER name asgnGrades A00123456 “Dent, Stu” 0000 0000 (reference) stealGrades 81 -99 7510098 869496100

40 Make Copies of Arrays n To protect array contents, make a copy public void setAsgnGrades(int[] newGrades) { if (areValidGrades(newGrades)) { if (areValidGrades(newGrades)) { for (int i = 0; i < asgnGrades.length; ++i) { for (int i = 0; i < asgnGrades.length; ++i) { asgnGrades[i] = newGrades[i]; asgnGrades[i] = newGrades[i]; } }} stu A_NUMBER name asgnGrades A00123456 “Dent, Stu” 0000 0000 (reference) stealGrades 81 -99 7510098 869496100 817510098 869496100

41 The Constructor n The constructor’s job is to give the first values to each of the instance variables  constructor needs to give a value to asgnGrades  just an array with eight zeroes »should have a constant for the eight values! public static final int NUM_ASGN = 8; public Student(String name) { … this.asgnGrades = new int[Student.NUM_ASGN]; this.asgnGrades = new int[Student.NUM_ASGN];}

42 Exercise n Create an IV, constructor, getter and setter for an object that holds exactly three numbers in an array  any three double values  setter accepts only arrays of length 3  make sure the numbers are “protected” »tho’ I don’t see why these would need to be….

43 More Methods n Get/set assignment grades individually  use 1-based index in the method int a1Grade = stu.getGrade(1); stu.setGrade(2, 100); stu A_NUMBER name asgnGrades A00123456 “Dent, Stu” 817510098 869496100 (reference) 100 81 a1Grade

44 getGrade Method n A1 stored in asgnGrades[0], and so on public int getGrade(int asgnNum) { if (1 <= asgnNum && asgnNum <= NUM_ASGN) { if (1 <= asgnNum && asgnNum <= NUM_ASGN) { return asgnGrade[asgnNum – 1]; return asgnGrade[asgnNum – 1]; } return 0; return 0;}  should make an isValidAsgnNo method »the setter will use it, too! »there’s an exercise for you!

45 More Methods n Calculate assignment average grade double aveGrade = stu.getAverage();  maybe another method that drops low scores? double aveWithDrops = stu.getAverageDropping(2) stu A_NUMBER name asgnGrades A00123456 “Dent, Stu” 817510098 869496100 (reference) 91.25 aveGrade 95.66667 aveWithDrops

46 Unmarked Assignments? n What if only two assignments graded?  still have zeroes on the rest  what does our average calculator do?  what should it do? stu A_NUMBER name asgnGrades A00123456 “Dent, Stu” 817500 0000 (reference) 19.5 aveGrade

47 Partly Full Arrays n Sometimes we want space for lots…  need space for all 8 assignment grades n …but using only some of them now  only two have been graded so far n Need to keep track of how many are in use  another variable – instance or class?  average method needs to use it

48 Unmarked Assignments? n Variable tracks # of assignments graded  update it after entering all students’ grades  method averages only graded assignments aveGrade = stu.getAverage(); stu A_NUMBER name asgnGrades A00123456 “Dent, Stu” 817500 0000 (reference) 78.0 aveGrade STUDENT NUM_ASGN gradedAsgns 8 2

49 Averaging Marked Assignments n Upper bound of the summing loop is the number of graded assignments  instead of NUM_ASGN public double getAverage() { int sum = 0; int sum = 0; for (int i = 0; i < gradedAsgns; ++i) { for (int i = 0; i < gradedAsgns; ++i) { sum += asgnGrades[i]; sum += asgnGrades[i]; } return (double)sum / (double)gradedAsgns; return (double)sum / (double)gradedAsgns;} Should maybe return 0 if gradedAsgns == 0. or this.asgnGrades[i] or Student.gradedAsgns

50 asgnGrades Getter Revisited n Maybe return only the part of asgnGrades that’s actually in use  that is, just the graded assignments int[] myGrades = stu.getAsgnGrades(); (reference) myGrades 8175 stu A_NUMBER name asgnGrades A00123456 “Dent, Stu” 817500 0000 (reference) STUDENT NUM_ASGN gradedAsgns 8 2

51 Exercise n If the number of spaces used is not available in the object or class, then it needs to be given to the method  Write a method to sum part of an array. For example… int sum3 = ArrayOperations.sumPartArray(arr, 3);  …sums the first three elements of arr

52 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