Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exam tip! str.equals(), str.startsWith(), str.toUpperCase() kbd.next(), kbd.nextLine(), etc Exam tip! str.equals(), str.startsWith(), str.toUpperCase()

Similar presentations


Presentation on theme: "Exam tip! str.equals(), str.startsWith(), str.toUpperCase() kbd.next(), kbd.nextLine(), etc Exam tip! str.equals(), str.startsWith(), str.toUpperCase()"— Presentation transcript:

1

2 Exam tip! str.equals(), str.startsWith(), str.toUpperCase() kbd.next(), kbd.nextLine(), etc Exam tip! str.equals(), str.startsWith(), str.toUpperCase() kbd.next(), kbd.nextLine(), etc Exam tip! Math.PI Exam tip! Math.PI

3  For reading data (kbd is a Scanner) kbd.nextInt() kbd.nextDouble() kbd.next() kbd.nextLine()  For checking strings (resp is a String) resp.equals(“yes”) resp.equalsIgnoreCase(“yes”) resp.startsWith(“y”) resp.toUpperCase().startsWith(“Y”) Exam tip! resp.toUpperCase() returns a String, so you can use startsWith(“Y”) right after!! Exam tip! resp.toUpperCase() returns a String, so you can use startsWith(“Y”) right after!! Exam tip! Technically we can do: kbd.nextLine().toUpperCase().toLowerCase().equalsIgnoreCase(“yes”) etc…. Exam tip! Technically we can do: kbd.nextLine().toUpperCase().toLowerCase().equalsIgnoreCase(“yes”) etc….

4  “Arguments” are given to the method  we also say that the method takes arguments Math.sqrt(10) – 10 is the (only) argument  asks Math for the square root of 10 Math.pow(5, 2) – 5 and 2 are both arguments  asks Math for 5 to the power 2 (i.e. 5 2 ) arguments must be in the right order!  Math.pow(2, 5) is 2 5, not 5 2

5  Arguments must be the right type! Math.pow(“fred”, true) makes no sense!  the two arguments must be numbers  doubles are OK: Math.pow(3.7, 1.98) resp.startsWith(7) makes no sense!  the argument must be a String: resp.startsWith(“7”)  And in the right order and there must be the right number of them!  Math.pow(5) and Math.pow(1, 2, 3) make no sense!

6  Assume the calls below are correct. What argument type(s) does each method take? Math.getExponent(3400.2) Math.ulp(2.6) Math.scalb(4.5, 2) str.split(“:”, “one:two:three:four”) str.length() str.regionMatches(true, 0, “this”, 7, 50)

7  Methods can return any kind of value  (or even none) Math.sqrt(10) returns a double value Math.max(3, 5) returns an int value kbd.nextInt() returns an int value kbd.next() returns a String value str.toUpperCase() returns a String value str.charAt(0) returns a char value

8  Assuming the code below is correct, what kind of value does each method return? double x, y = 3.2; int n = 42; String name = “Mark”; boolean good; name = name.replaceFirst(“a”, “o”); x = Math.exp(y); n = Math.getExponent(x); good = (name.equalsIgnoreCase(“mork”));

9  Void or value-returning? & what kind of value does each VRM return? if (answer.startsWith(“Y”)) { double x = Math.pow(3, 6); int n = kbd.nextInt(); System.out.println(“Hello!”); myWin.setVisible(true); double cm = Converter.cmFromFeetInches(n, x); thingamajig.doStuff(cm, x, that.get(n)); } Note: there are two method calls on the last line. How can we find out what kind of value get returns?

10  Header: 1. public/private 2. static (or non-static) 3. return-type (void, int, double, String, boolean, Class, etc) 4. methodName 5. (paramType1 param1, paramType2 param2, …) E.g.)  public static double fahrenheitFromCelsius(double degC)  public boolean equalsTo(int a, int b)  private int subtract(int a, int b) Exam tip! Write a method that takes and returns Takes  parameters Returns  return type Exam tip! Write a method that takes and returns Takes  parameters Returns  return type

11  Arguments are values (10, 15.4, “Hello”)  Parameters are variables need to be declared like variables  (double degC), (int ft, double in) only differences are:  declarations are separated by commas, not ;s  every parameter needs its own type, even if they’re all the same type:  (double x, double y, double z), (int a, int b) Exam tip! Given a list of parameters, a method call needs to have corresponding argument list! Exam tip! Given a list of parameters, a method call needs to have corresponding argument list! Exam tip! Empty () means no parameters expected for that method, but you still need ()!!!! Exam tip! Empty () means no parameters expected for that method, but you still need ()!!!!

12  The method body is where you tell the computer how to compute the value needed, etc  how to convert feet and inches to cm  how to convert Celsius to Fahrenheit ...  Need to know how to do it...  feet times 12 plus inches, all multiplied by 2.54 ...and translate it into Java: result = (ft * 12 + in) * 2.54;

13  Anything you can do in main …  …you can do in a method (local) variable declarations (including objects) assignment statements selection controls (if, if-else, if-else-if) repetition controls (while, for) method calls (other things we haven’t learned about yet)

14  Our methods need return commands need to return the right kind of thing we want to return exactly the right value but Java doesn’t care!  So we can just put a “dummy” return in return something so that Java doesn’t complain worry about making it right later we call such a function a “stub” (it’s short) Exam tip! Your method stubs should compile with proper parameter lists and return types! void method stubs “can” have a single println statement to print out some info, but not required for the exams! Exam tip! Your method stubs should compile with proper parameter lists and return types! void method stubs “can” have a single println statement to print out some info, but not required for the exams!

15 public String getLetterGrade () { return “”;//return ANY String } public int getGrade () { return 1000;//return ANY integer } return statement is the last line of a method! public void printStudentRecord () { //void doesn’t need anything for stub }

16  Method names in mixed case capital letter for 2 nd and subsequent words  The same as variable’s naming convention

17 public static returnType methodName(pType1 p1, pType2 p2) { body... return result; }  returnType, pType1 and pType2 are int, or double, or String, or Class, or an array, or any data type we’ve seen! It can be void, which doesn’t return anything  methodName is the name of the method p1 and p2 are the parameters  body is for the commands calculating the result  static is only needed for class (static) methods

18  Classes can be used right away MyUtilities.pause() ;  so long as we can “see” them  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 Exam tip! static methods! Exam tip! static methods!

19  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;

20 public class Student { private String aNumber;// A00... private String name;// family name, givens private int pctGrade;// 0..100 … } Exam tip! instance variables are declared private (not public) not “static”; not “final”! Exam tip! instance variables are declared private (not public) not “static”; not “final”!

21  Access modifiers public private  Non-access modifiers static final

22  Instance variables private dataType varName  Class variables private static dataType varName  Instance constant public final dataType CONST_NAME  Class constant public static final dataType CONST_NAME Exam tip! Class  static Constant  final Exam tip! Class  static Constant  final

23  Constructor “builds” the object gives a value to each of the instance variables private String aNumber;// A00… private String name;// Last, First private int grade;// 0.. 100 public Student(String a, String n, int g) { aNumber = a; name = n; grade = g; } a, n, and g are the parameters: the values the caller wants to use; aNumber, name, and grade are the instance variables: the values we will use.

24  Generally declared public anyone can build a Scanner, a Student, …  Name is exactly the same as the class name class Student  constructor named “Student” class Animal  constructor named “Animal”  No return type not even void!  Argument for each instance variable (often)

25  Their job is to give a value to each instance variable in the class and so often just a list of assignment commands  instanceVariable = parameter; aNumber = a; name = n; grade = g;  But may want to check if values make sense so maybe a list of if-else controls

26  If given value makes no sense, use a default  but still instanceVariable = (something); public Student(String a, String n, int g) { if (a.startsWith(“A”) && a.length() == 9) { aNumber = a; } else { aNumber = “(illegal)”; } name = n; … } Exam tip! Given object instantiation, write a constructor! int r, g, b; r = g = b = 0; Colour col = new Colour(r,g,b); Set values of r, g, b if between [0,255] Otherwise zero Exam tip! Given object instantiation, write a constructor! int r, g, b; r = g = b = 0; Colour col = new Colour(r,g,b); Set values of r, g, b if between [0,255] Otherwise zero

27 Student stu = new Student(“A00000000”, “Dent, Stu”, 100);  The argument list should match the parameter list of the constructor (String a, String n, int g)  The same as any other method calls public static double max(double a, double b){…} double a = 12.5; double b = 12.6; if (Math.max(a, b)) {}

28  Given the following object instantiation code, write an appropriate constructor (stub) of the class Car: Car c1 = new Car("Toyota","Corolla“,2013);  Answer: public Car(String maker, String model, int year) { } Exam tip! Matching arguments and parameters Exam tip! Matching arguments and parameters

29  Getters: public String getANumber() { return aNumber; }  Setters: public void setPctGrade(int newGrade) { if (0 <= grade && grade <= 100) { pctGrade = newGrade; } Exam tip! Getters: public! Anyone can ask! Return type! Never void! Non-static! Each student has own name! Just return the instance variable! Exam tip! Getters: public! Anyone can ask! Return type! Never void! Non-static! Each student has own name! Just return the instance variable! Exam tip! Setters: public! Anyone can change! Return type! (usually) void! Non-static! Each student has own grade! Set the value (with some conditions) Exam tip! Setters: public! Anyone can change! Return type! (usually) void! Non-static! Each student has own grade! Set the value (with some conditions)

30  Write getters/setters for: private String name; private double temperature; private int count; Exam tip! Setters may need some error checking: e.g.) setTempearature should sets the value only if the new value is larger than or equal to -273.15 degrees Celsius. Exam tip! Setters may need some error checking: e.g.) setTempearature should sets the value only if the new value is larger than or equal to -273.15 degrees Celsius.

31  Definition from the textbook: “Within a method definition, you can use the keyword this as a name for the object receiving the method call.”

32 public class SomeClass { private int var; public SomeClass(){ this.var = 0;//instance variable var = 0;//instance variable } public void incrementVar(int var){ this.var++;//instance variable var++;//local parameter!!! } public void printVar(){ System.out.println(this.var);//instance variable System.out.println(var);//instance variable }} Exam tip! this is only needed to disambiguate things. Exam tip! this is only needed to disambiguate things.

33  Instance variables/methods Belongs to a particular object Each instance/object of the class has its own value IM uses object’s values (IV)  Class (static) variables/methods Belongs to a particular class All the instances/objects of the class point to the same CV (hence, the same value) CM uses CV (static) values

34  final means once it’s assigned a value, you cannot change it (immutable)!  Can be static and final (class constant)  Or non-static and final (instance constant)

35 You may bring a reference sheet:  A single 8.5x11 (A4) sheet of paper.  It may be hand-written or printed.  You may use both sides of the sheet.  You can prepare it alone or with friends, but bring your own copy (no sharing copies during the test).  If your sheet is too large (or otherwise breaks the rules), it will be confiscated.


Download ppt "Exam tip! str.equals(), str.startsWith(), str.toUpperCase() kbd.next(), kbd.nextLine(), etc Exam tip! str.equals(), str.startsWith(), str.toUpperCase()"

Similar presentations


Ads by Google