35
CSCI 1226 FALL 2015 Midterm #2 Reviews

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

Embed Size (px)

Citation preview

CSCI 1226 Winter 2015 Midterm #2 Reviews

CSCI 1226 FALL 2015 Midterm #2 ReviewsMethodsExam tip!str.equals(), str.startsWith(), str.toUpperCase()kbd.next(), kbd.nextLine(), etcExam tip!Math.PI MethodsFor 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!Technically we can do: kbd.nextLine().toUpperCase().toLowerCase().equalsIgnoreCase(yes) etc.ArgumentsArguments are given to the methodwe also say that the method takes argumentsMath.sqrt(10) 10 is the (only) argumentasks Math for the square root of 10Math.pow(5, 2) 5 and 2 are both argumentsasks Math for 5 to the power 2 (i.e. 52)arguments must be in the right order!Math.pow(2, 5) is 25, not 52Argument TypesArguments must be the right type!Math.pow(fred, true) makes no sense!the two arguments must be numbersdoubles 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 orderand there must be the right number of them!Math.pow(5) and Math.pow(1, 2, 3) make no sense!ExerciseAssume 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)Return TypesMethods can return any kind of value(or even none)Math.sqrt(10) returns a double valueMath.max(3, 5) returns an int valuekbd.nextInt() returns an int valuekbd.next() returns a String valuestr.toUpperCase() returns a String valuestr.charAt(0) returns a char value

ExerciseAssuming 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));ExerciseVoid 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?Method declarationHeader:public/privatestatic (or non-static)return-type (void, int, double, String, boolean, Class, etc)methodName(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 parametersReturns return typeArguments and ParametersArguments are values (10, 15.4, Hello)Parameters are variablesneed to be declared like variables(double degC), (int ft, double in)only differences are:declarations are separated by commas, not ;severy parameter needs its own type, even if theyre 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!Empty () means no parameters expected for that method, but you still need ()!!!!Method BodyThe method body is where you tell the computer how to compute the value needed, etchow to convert feet and inches to cmhow 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; Method BodyAnything you can do in mainyou can do in a method(local) variable declarations (including objects)assignment statementsselection controls (if, if-else, if-else-if)repetition controls (while, for)method calls(other things we havent learned about yet)Method StubsOur methods need return commandsneed to return the right kind of thingwe want to return exactly the right valuebut Java doesnt care!So we can just put a dummy return inreturn something so that Java doesnt complainworry about making it right laterwe call such a function a stub (its 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!Method Stubspublic 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 doesnt need anything for stub}

Naming MethodsMethod names in mixed casecapital letter for 2nd and subsequent wordsThe same as variables naming conventionPutting them togetherpublic 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 weve seen! It can be void, which doesnt return anythingmethodName is the name of the methodp1 and p2 are the parametersbody is for the commands calculating the resultstatic is only needed for class (static) methods

Classes vs. ObjectsClasses can be used right awayMyUtilities.pause();so long as we can see themObjects need to be createdexcept for Strings, which are so massively usefulScanner kbd = new Scanner(System.in);objects contain datadifferent objects have different datamethods are mostly about that dataExam tip!static methods!Declaring ObjectsMost Java objects created using newusually with argumentsarguments depend on the classkbd = new Scanner(System.in);rover = new Animal(Animal.DOG);// I made this up!c1 = new Color(255, 127, 0);// This is orangeokButton = new JButton(OK);not Strings, thos1 = Strings are special!;s2 = new String(But this works, too!);Remember to import java.awt.Color;import javax.swing.JButton;Student Class (Start)public class Student {private String aNumber;// A00...private String name;// family name, givensprivate int pctGrade;// 0..100}Exam tip!instance variables are declared private (not public)not static; not final!Java modifiersAccess modifierspublicprivateNon-access modifiersstaticfinal

Which modifiers?Instance variablesprivate dataType varNameClass variablesprivate static dataType varNameInstance constantpublic final dataType CONST_NAMEClass constantpublic static final dataType CONST_NAME

Exam tip!Class staticConstant finalConstructorsConstructor builds the objectgives 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. ConstructorsGenerally declared publicanyone can build a Scanner, a Student, Name is exactly the same as the class nameclass Student constructor named Studentclass Animal constructor named AnimalNo return typenot even void!Argument for each instance variable (often) ConstructorsTheir job is to give a value to each instance variable in the classand so often just a list of assignment commandsinstanceVariable = parameter;aNumber = a;name = n;grade = g;But may want to check if values make senseso maybe a list of if-else controlsChecking ValuesIf given value makes no sense, use a defaultbut 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 zeroCreate a Student objectStudent 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 callspublic static double max(double a, double b){}

double a = 12.5;double b = 12.6;if (Math.max(a, b)) {}

ExerciseGiven 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 parametersGetters and SettersGetters:public String getANumber() { return aNumber;}Setters:public void setPctGrade(int newGrade) { if (0