Presentation is loading. Please wait.

Presentation is loading. Please wait.

Review of CSCI 1226 More of What You Should Already Know.

Similar presentations


Presentation on theme: "Review of CSCI 1226 More of What You Should Already Know."— Presentation transcript:

1 Review of CSCI 1226 More of What You Should Already Know

2 Review of Chapters 5 to 7 n Methods »(AKA subroutines, functions, procedures)  understand method calls  create and use our own methods  organize methods into classes n Data type classes  create and use a data type class

3 Using Methods n We’ve been using methods from the start  print and println are methods (as is printf)  nextInt, nextDouble, next, and nextLine, too  equals, equalsIgnoreCase, startsWith, and all those other things we can ask a String to do  pow, sqrt, max, min, and all those other things we can ask Math to do

4 Why Do We Have Methods? n Code Re-use  Doing “same” thing in multiple places » we do a lot of printing! n Code Hiding (Encapsulation)  Secret  Implementation independence n Code Abstraction  Top-down design

5 Parts of a Method Call n All method calls are alike:  Math.pow(5, 7)  kbd.nextInt()  resp.equalsIgnoreCase(“yes”)  Someone.doSomething(with, these) »Someone (Math, kbd, resp, …) »doSomething (pow, nextInt, equalsIgnoreCase, …) »(with, these) ((5, 7), (), (“yes”))

6 Someone? n Can ask a class or an object  class name starts with a capital letter (Math)  object name starts with a little letter (kbd) n Objects are variables with a class data type Scanner kbd = new Scanner(System.in); String resp = kbd.nextLine(); n Methods are declared in that class  class Math, class Scanner, class String, …

7 doSomething? n Name of the method says what it does…  print, println, … »verb phrase in the imperative (do, be) n …or what it gives us…  length, nextInt, nextLine, … »noun phrase n …or what it tells us  equals, equalsIgnoreCase, startsWith »verb phrase in the declarative (does, is)

8 With These? n Method needs more information n “Arguments” are given to the method »we also say that the method takes arguments  Math.pow(5, 7) – 5 and 7 are both arguments  resp.startsWith(“y”) – “y” is the (one) argument n Some methods take no arguments  kbd.nextLine() – needs no more information

9 Void Methods n Some methods are complete commands in themselves  telling the computer to do something System.out.println(“A complete command”); n These methods cannot be used as part of a command String resp = System.out.println(“What???”);

10 Return Values n Some methods return values  Math.sqrt(x) returns the square root of x  kbd.nextInt() returns the next (int) value n These (usually) used as part of a command int n = kbd.nextInt(); double y = Math.sqrt(n); if (resp.startsWith(s)) { n But may be used alone sometimes kbd.nextLine(); // we don’t care what the line was!

11 “Chaining” Method Calls n When one method returns an object value…  e.g. resp.toUpperCase()  if resp is “yes”, resp.toUpperCase() is “YES” n …we can ask that object a question  e.g. resp.toUpperCase().startsWith(“Y”)  resp is “yes” (which doesn’t start with “Y”)  resp.toUpperCase() is “YES”  “YES” does start with “Y”

12 The Job of the Method n Every method has a job to do  print a line, get the next int, … n Call the method  the job gets done  that’s what the method is there for n How the method does the job…  the body/definition of the method n …is just details!  caller (“client”) just wants it done

13 Make Gift Exchange 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

14 Make Gift Exchange 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 }

15 Make Gift Exchange List public static void main(String[] args) { // get a list of everyone giving presents String[] giving = GiftExchange.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?

16 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

17 Static Methods calling Methods n Location of the method is the current class  method getGivingList is in class GiftExchange GiftExchange.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

18 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.

19 Make Gift Exchange 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() {// STUB! return new String[1]; }

20 Make Gift Exchange 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?

21 Make Gift Exchange 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 }

22 Make Gift Exchange 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?

23 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!

24 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!

25 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!

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

27 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

28 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 // prompt for and read a name into that element // prompt for and read a name into that element // return the array // return the array // STUB – delete when above is complete: return new String[1]; return new String[1];}

29 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 if (list[i].equals(name)) { if (list[i].equals(name)) { // remove that element // remove that element list[i] = “”; list[i] = “”; } }} Angela Barrak 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.

30 Organizing Methods into Classes n Above methods are just for the program n May want methods that are generally useful  to do math (Math.pow, Math.sqrt, …)  for arrays (Arrays.toString, Arrays.sort, …)  we can make our own public class Converter { public class Utilities{  methods written same way  just leave out main! I use green text for code in a non-program class.

31 Classes vs. Objects n Classes can be used right away Utilities.printTitle(“Utilities Demo”); »so long as we can “see” them n Objects need to be created »except for Strings, which are so massively useful… Scanner kbd = new Scanner(System.in);  objects contain data  different objects have different data  methods are mostly about that data

32 Object Oriented Programming n Programming arranged around objects  main program creates the objects  objects hold the data  objects call each others’ methods  objects interact to achieve program goal n Very important in GUI programs  Graphical User Interface »WIMP (Windows, Icons, Menus, Pointers) interface

33 What are Objects? n An object in a program often represents a real-world object…  an animal, a vehicle, a person, a university, … n …or some abstract object…  a colour, a shape, a species, … n …or some thing the program needs to track  a string, a window, a GUI button, …

34 Object (Data Type) Classes n What kind of object it is  its data type is a Class String s1, s2;// s1 & s2 are Strings Scanner kbd, str;// kbd & str are Scanners Animal rover, hammy;// rover & hammy are Animals Color c1, c2;// c1 & c2 are Colors JButton okButton, cancelButton;// … are JButtons n Objects in the same class do the same kinds of things To use Color & JButton, you need to import java.awt.Color; import javax.swing.JButton;

35 Declaring Objects n Most Java objects created using new »usually with arguments »arguments depend on the class kbd = new Scanner(System.in); rover = new Animal(Animal.DOG);// I made this up! c1 = new Color(255, 127, 0);// This is orange okButton = new JButton(“OK”); »not Strings, tho’ s1 = “Strings are special!”; s2 = new String(“But this works, too!”); Remember to import java.awt.Color; import javax.swing.JButton;

36 Object Data and Methods n Each kind of object has its own kind of data  String has array of characters  Color has red, green, and blue components n Methods access that data  get pieces of it, answer questions about it, change it name characters Mark Young orange red green blue 255 127 0

37 Making Our Own Data Types n When we want to represent objects but can’t find an existing class for that kind of object  e.g. Student objects n Identify the objects’ data and operations  data: A-number, name, address, grades, …  operations: change name, print address label, set grades, calculate GPA, … n Create a class for this kind of object

38 Instance Variables public class Student { public final String A_NUMBER;// A00... private String name;// family name, givens private int pctGrade;// 0..100 …}  instance variables are declared private (not public) »don’t let anyone change them without our permission  may be final (never going to change) »these may be declared public

39 Declaring a Student n Give A#, name and grade when create Student s1, s2; s1 = new Student(“Dent, Stu”, 81); s2 = new Student(“Tudiaunt, A.”, 78);  or can combine the steps: Student s3 = new Student(“No, Dr.”, 0);  arguments are name (String) and grade (int) »values for each (or some of the) instance variable

40 Student Constructor n Constructor “builds” the Student object  gives a value to each of the instance variables public final String A_NUMBER;// A00… private String name;// Last, First private int grade;// 0.. 100 public Student(String name, int grade) { this.name = name; this.name = name; this.grade = grade;// should check this value! this.grade = grade;// should check this value! … // A_NUMBER still needs a value … // A_NUMBER still needs a value} note how “name” and “this.name” are used.

41 Giving Values n Constructor’s job is to give values to all instance variables  client may say what values to use »may need to check those values to see if they’re OK  client may leave some values unstated »we choose those values ourselves

42 Checking Values n Grade should be 0..100  write a method to check if it is in that range public static boolean isValidGrade(int g) { return 0 <= g && g <= 100; return 0 <= g && g <= 100;} n Note: static method  whether grade is valid is same for all Students »static  same for every object of this class »non-static  diff. objects may give diff. answers What should we do about that “magic” number???

43 Choosing Values n May use a reasonable default value  if they don’t say what grade, set grade to 0 n May generate our own values  A-numbers automatically generated »1 st Student  A00000001 »2 nd Student  A00000002  static method to generate those numbers  static variable to remember the count

44 Generating A-Numbers n Static variable to remember what’s next private static int howManyStudents = 0; n Method to generate next A-Number  increment howManyStudents & generate String private static String nextANumber() { ++howManyStudents; ++howManyStudents; return String.format(“A%08d”, howManyStudents); return String.format(“A%08d”, howManyStudents);}  method is private so others can’t use it! »they might try to misuse it!

45 Student Constructor n All instance variables given values!  gives a value to each of the instance variables public Student(String name, int grade) { this.name = name; this.name = name; if (isValidGrade(grade)) { if (isValidGrade(grade)) { this.grade = grade; this.grade = grade; } else { } else { this.grade = 0; this.grade = 0; } A_NUMBER = nextANumber(); A_NUMBER = nextANumber();} Good practice: call only static methods from your constructor.

46 Overloaded Constructor n May want more than one constructor  let client decide how much/what info. to give Student s1 = new Student(“Alice”, 100); Student s2 = new Student(“Ben”);  need a constructor that takes just a String n Re-use code as much as possible  have new constructor call old constructor public Student(String name) { this(name, 0);// use name given; set grade to 0 this(name, 0);// use name given; set grade to 0}

47 Methods to Get Information n Instance variables are private  client can’t use them! System.out.println(stu.name); n “Getters”  usually named get + name of instance variable »but capitalized in camelCase System.out.println(stu.getName()); System.out.println(stu.getPctGrade()); name is private in Student!

48 Student “Getters” n Getters are very simple!  just return the instance variable »method return type same as type of variable public String getName() { return name; return name;} public String getPctGrade() { return grade; return grade;} public! Anyone can ask! No static! Each student has own name!

49 Methods to Change Information n Some fields may need to be changed  name and grade, for example  student number should NOT be changed! n Need a method to do that, too! stu.name = “Dummikins, Dummy”; n Methods called “setters”  named “set” + name of instance variable stu.setName(“Dummikins, Dummy”); stu.setPctGrade(1000000); name is private in Student!

50 Setters n Given the new value the caller wants  normally we will use that value public static void setName(String newName) { name = newName; name = newName;}  but we might want to reject it public static void setPctGrade(int newGrade) { if (isValidGrade(grade)) { if (isValidGrade(grade)) { grade = newGrade; grade = newGrade; }} May want to print an error message…

51 More Methods n Can create other methods if you want stu.printRecord();  prints stu’s name, A-number and grade  just uses System.out.println »that’s OK because it’s part of the job! stu number name pctGrade A00123456 “Dent, Stu” 81 A-Number: A00123456 Name: Dent, Stu Grade: 81

52 Class (static) Methods n Ask for letter grade corresponding to pct String lg = Student.letterGradeFor(stu.getPctGrade());  doesn’t matter who you ask, answer is same »static method! public static String letterGradeFor(int g) { if (g >= 80) return “A”; else if (g >= 70) return “B”; … if (g >= 80) return “A”; else if (g >= 70) return “B”; …}

53 More Instance Methods n Make it easier to get Student’s letter grade S.o.pln(stu.getName() + “ got ” + stu.getLetterGrade());  asks student object for its letter grade  method is like a getter… public String getLetterGrade() { return this.getLetterGradeFor(this.getPctGrade()); return this.getLetterGradeFor(this.getPctGrade());}  …but don’t create a letterGrade variable!

54 Programming Principles n Make it impossible (or very hard) for the client to do stupid/malicious things  can’t set pctGrade outside 0..100  can’t set pctGrade to 100 and letterGrade to F n Make it easy for client to do common things  ask a Student for their letter grade, even tho’ could ask Student for their pctGrade and then translate it using “cascading if” control  getLetterGrade is a convenience

55 Another Convenience n Printing an object doesn’t work very well! Student stu = new Student(“Pat”, 80); System.out.println(stu);  prints something like Student@1f23a  want something like Pat (A00000003) n toString method tells how to convert an object to a String (which can be printed) System.out.println(stu.toString());

56 The toString Method n Does not print anything!  it returns the String that will get printed @Override public String toString() { return name + “ (” + A_NUMBER + “)” return name + “ (” + A_NUMBER + “)”}  @Override is optional, but NetBeans will tell you to put it there »I’ll explain what it means later this term

57 Using the toString method n You can ask for it: Student s = new Student(“Pat”, 80); System.out.println(s.toString()); n But you don’t actually need to! Student s = new Student(“Pat”, 80); System.out.println(s);  println will actually change it to String itself »one of the conveniences println provides!

58 Questions? n Next Time  material from chapters 1-7 that we skipped in CSCI 1226


Download ppt "Review of CSCI 1226 More of What You Should Already Know."

Similar presentations


Ads by Google