Presentation is loading. Please wait.

Presentation is loading. Please wait.

Week 15 – Friday.  Student Questions  Review up to Exam 2  Loops  Arrays  StdDraw  StdAudio  Static methods.

Similar presentations


Presentation on theme: "Week 15 – Friday.  Student Questions  Review up to Exam 2  Loops  Arrays  StdDraw  StdAudio  Static methods."— Presentation transcript:

1 Week 15 – Friday

2  Student Questions  Review up to Exam 2  Loops  Arrays  StdDraw  StdAudio  Static methods

3

4

5

6

7

8  If you declare a lot of references, you have not created any objects, just lots of arrows (unlike primitive types) Eggplant aubergine; DumpTruck truck1; Idea thought; Eggplant aubergine; DumpTruck truck1; Idea thought; aubergine truck1thought

9  To make a new object, you use the new keyword with the name of the class followed by parentheses:  Perhaps there is a Ham constructor that lets you take a double that is the number of pounds that the ham weighs: Ham ham1 = new Ham(); //default constructor Ham ham2 = new Ham( 4.2 ); //weight constructor

10  You are already familiar with calling methods on String s  So, applying this knowledge to other objects should be a piece of cake  Simply type the name of the object, put a dot, then type the method name, with the arguments in parentheses: String s = new String("Help me!"); char c = s.charAt(3); //c gets 'p' String s = new String("Help me!"); char c = s.charAt(3); //c gets 'p'

11  Just like calling methods on String objects:  You’ve learned lots of methods that work on String objects  Every kind of object has its own methods  You’ll have to learn them (or look them up) if you want to use them Ham h = new Ham(3.2); h.bite(); //takes bite out of ham double weight = h.getWeight(); //gets current ham weight Ham h = new Ham(3.2); h.bite(); //takes bite out of ham double weight = h.getWeight(); //gets current ham weight

12  In this example, the == operator will say they are different, but the equals() method will say that they are the same  Every object has an equals() method String s1 = new String("identical"); String s2 = new String("identical"); if( s1 == s2 ) System.out.println("Same!"); else System.out.println("Different!"); if( s1.equals( s2 ) ) System.out.println("Same!"); else System.out.println("Different!"); String s1 = new String("identical"); String s2 = new String("identical"); if( s1 == s2 ) System.out.println("Same!"); else System.out.println("Different!"); if( s1.equals( s2 ) ) System.out.println("Same!"); else System.out.println("Different!");

13

14  An object is the actual data that you can use in your code  A class is a template whereby you can create objects of a certain kind  Class =Car  Object=Mitsubishi Lancer Evolution X  Just like int is a type and 34 is an instance of that type  A key difference is that you can define new classes  Classes contain members and methods

15 public class Name { private int member1; private double member2; private Hedgehog member3; public Name() { … } public int method1( double x ){ … } Class definition Member declarations Constructor definition Method definition

16  Members are the actual data inside an object  They can be primitive types or other object types  They are usually hidden ( private ) from the outside world public class Point { private double x; // member variable private double y; // member variable } public class Point { private double x; // member variable private double y; // member variable }

17  private and public allow you to specify the scope or permissions of members and methods  private means that only methods from the same class can access an item  public means that any method can access the item  protected means that child classes can access the data (but not someone outside of the inheritance hierarchy)

18  Methods allow you to do things  Object methods usually allow you to manipulate the members  They are usually visible ( public ) to the outside world  Methods can be static or non-static  Only non-static methods can interact with the members of an object

19  Constructors are a special kind of method  They allow you to customize an object with particular attributes when it is created public class Point { private double x; // member variable private double y; // member variable public Point( double newX, double newY ) { //constructor x = newX; y = newY; } public class Point { private double x; // member variable private double y; // member variable public Point( double newX, double newY ) { //constructor x = newX; y = newY; }

20  Because members are usually private, it is common to use methods specifically just to find out what their values are  A method that just returns the value of a member variable is called an accessor public double getX() { //accessor for x return x; } public double getY() { //accessor for y return y; } public double getX() { //accessor for x return x; } public double getY() { //accessor for y return y; }

21  Again, because members are usually private, it is common to use methods specifically just to change their values  A method that just changes the value of a member variable is called a mutator public void setX( double newX ) { //mutator for x x = newX; } public void setY( double newY ) { //mutator for y y = newY; } public void setX( double newX ) { //mutator for x x = newX; } public void setY( double newY ) { //mutator for y y = newY; }

22

23  Static members are stored with the class, not with the object public class Item { private static int count = 0; //only one copy (in class) private String name;//one copy per object public Item( String s ) { name = s; count++;//updates global counter } public String getName() { return name; } public static int getItemsInUniverse() { return count; } } public class Item { private static int count = 0; //only one copy (in class) private String name;//one copy per object public Item( String s ) { name = s; count++;//updates global counter } public String getName() { return name; } public static int getItemsInUniverse() { return count; } }

24  Static members are also called class variables  Static members can be accessed by either static methods or regular methods (unlike normal members which cannot be accessed by static methods)  Static members can be either public or private

25  Sometimes a value will not change after an object has been created:  Example: A ball has a single color after it is created  You can enforce the fact that the value will not change with the final keyword  A member declared final can only be assigned a value once  Afterwards, it will never change

26

27  We want to compare the running time of one program to another  We want a mathematical description with the following characteristics:  Worst case We care mostly about how bad things could be  Asymptotic We focus on the behavior as the input size gets larger and larger

28  Just adding up the total operations in code is not very helpful because:  It cannot be used to give us an idea of how long the program really runs in seconds  It is complex and unwieldy  The most important thing about the analysis of the code that we did is learning that the growth of the function should be linear  A general description of how the running time grows as the input grows would be useful

29  Enter Big Oh notation  Big Oh simplifies a complicated running time function into a simple statement about its worst case growth rate  All constant coefficients are ignored  All low order terms are ignored  3n + 3 is O(n)  Big Oh is a statement that a particular running time is no worse than some function, with appropriate constants

30  147n 3 + 2n 2 + 5n + 12083 is O(n3)O(n3)  n 1000 + 2 n is O(2 n )  15n 2 + 6n + 7log n + 145 is O(n2)O(n2)  659n + nlog n + 87829 is O(n log n)  Note: In CS, we use log 2 unless stated otherwise

31  Here is a table of several different complexity measures, in ascending order, with their functions evaluated at n = 100 DescriptionBig Ohf(100) ConstantO(1)1 LogarithmicO(log n)6.64 LinearO(n)O(n)100 LinearithmicO(n log n)664.39 QuadraticO(n2)O(n2)10000 CubicO(n3)O(n3)1000000 ExponentialO(2 n )1.27 x 10 30 FactorialO(n!)9.33 x 10 157

32

33  For a linear search, we just look through every element in the array until we find it or run out  If we find it, we return the index, otherwise we return -1  This takes O(n) time where n is the length of the array public static int find( int[] array, int number ) { for( int i = 0; i < array.length; i++ ) if( array[i] == number ) return i; return -1; } public static int find( int[] array, int number ) { for( int i = 0; i < array.length; i++ ) if( array[i] == number ) return i; return -1; }

34  We can search faster if the array is already sorted by playing a high-low game  Repeatedly divide the search space in half  We’re looking for 37, let’s say 542331 Check the middle (Too high) Check the middle (Too low) Check the middle (Too low) Check the middle (Found it!) 37

35  We cut the search space in half every time  At worst, we keep cutting n in half until we get 1  Let’s say x is the number of times we look:  The running time is O(log n) log n = x n = 2 x n = 1

36  It is very simple to understand  It is very simple to code  It is not very fast  The idea is simply to go through your array, swapping out of order elements until nothing is out of order

37  One “pass” of the bubble sort algorithm goes through the array once, swapping out of order elements for(int j = 0; j < array.length - 1; j++) if( array[j] > array[j + 1] ) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } for(int j = 0; j < array.length - 1; j++) if( array[j] > array[j + 1] ) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; }

38  The full Java method for bubble sort would require us to have at least n – 1 passes  Alternatively, we could keep a flag to indicate that no swaps were needed on a given pass for(int i = 0; i < array.length – 1; i++) for(int j = 0; j < array.length - 1; j++) if( array[j] > array[j + 1] ) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } for(int i = 0; i < array.length – 1; i++) for(int j = 0; j < array.length - 1; j++) if( array[j] > array[j + 1] ) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; }

39

40

41  The Color class is how Java keeps track of colors, using an RGB model  To use it, you need to type import java.awt.Color; at the top of your program (before the class declaration)  Each Color object represents one of 16,777,216 different colors with a value between 0-255 for Red, Green, and Blue

42  To create a custom color:  Create colors using the constructor to specify RGB values  Get individual values using:  getRed()  getGreen()  getBlue() Color c = new Color(255,165,0); //orange int green = c.getGreen(); Color c = new Color(255,165,0); //orange int green = c.getGreen();

43  If the R, G, B values happen to be the same, the color is a shade of gray  255, 255, 255 = White  128, 128, 128 = Gray  0, 0, 0 = Black  To convert a color to a shade of gray, use the following formula:  Value =.3R +.59G +.11B  Based on the way the human eye perceives colors as light intensities

44 012 0 A 1 B 2 C 3 D 012 0 A 1 B 2 C 3 D OriginalMirrored

45  Using the picture class, here is the code for mirroring Picture picture = new Picture( file ); //the picture to be mirrored Picture mirrored = new Picture( picture.width(), picture.height() ); for( int i = 0; i < picture.width(); i++ ) for( int j = 0; j < picture.height(); j++ ) mirrored.set( picture.width() - i - 1, j, picture.get( i, j ) ); Picture picture = new Picture( file ); //the picture to be mirrored Picture mirrored = new Picture( picture.width(), picture.height() ); for( int i = 0; i < picture.width(); i++ ) for( int j = 0; j < picture.height(); j++ ) mirrored.set( picture.width() - i - 1, j, picture.get( i, j ) );

46 012 0 A 1 B 2 C 3 D 0123 0 DCBA 1 2 Original Rotated

47  Using the picture class, here is the code for rotation Picture picture = new Picture( file ); //the picture to be rotated Picture rotated = new Picture( picture.height(), picture.width() ); for( int i = 0; i < picture.width(); i++ ) for( int j = 0; j < picture.height(); j++ ) rotated.set( picture.height() - j - 1, i, picture.get( i, j ) ); Picture picture = new Picture( file ); //the picture to be rotated Picture rotated = new Picture( picture.height(), picture.width() ); for( int i = 0; i < picture.width(); i++ ) for( int j = 0; j < picture.height(); j++ ) rotated.set( picture.height() - j - 1, i, picture.get( i, j ) );

48

49  The idea of inheritance is to take one class and generate a child class  This child class has everything that the parent class has (members and methods)  But, you can also add more functionality to the child  The child can be considered to be a specialized version of the parent

50  The key idea behind inheritance is safe code reuse  You can use old code that was designed to, say, sort lists of Vehicle s, and apply that code to lists of Car s  All that you have to do is make sure that Car is a subclass (or child class) of Vehicle

51  Java respects the subclass relationship  If you have a Vehicle reference, you can store a Car object in that reference  A subclass (in this case a Car ) is a more specific version of the superclass ( Vehicle )  For this reason, you can use a Car anywhere you can use a Vehicle  You cannot use a Vehicle anywhere you would use a Car

52  We use the extends keyword to create a subclass from a superclass  A Car can do everything that a Vehicle can, plus more public class Car extends Vehicle { private String model; public Car(String s) { model = s; } public String getModel() { return model; } public void startEngine() { System.out.println("Vrooooom!"); } public class Car extends Vehicle { private String model; public Car(String s) { model = s; } public String getModel() { return model; } public void startEngine() { System.out.println("Vrooooom!"); }

53

54  It is possible to read and write individual pieces of data to a text file  Files are great because they exist after the program is done  Reading and writing to a file is very similar to reading and writing to the command line (using Scanner and System.out )

55  Reading from a text file uses Scanner, just like reading from the command line  We just have to create a new File object that gives the file we want to read from  This code will read from some file called input.txt, as if someone were typing its contents into the command line Scanner in = new Scanner(new File("input.txt"));

56  Java loves objects  If you want to write to a file, you've got to create a PrintWriter object, based on a FileOutputStream object (which takes the file name as a parameter)  Once you've got a PrintWriter, you can use it just like System.out PrintWriter out = new PrintWriter(new FileOutputStream ("output.txt"));

57  Using Scanner or PrintWriter to open a file for reading or writing can throw an exception  The easiest way to fix the problem is to throw the exception up to the next level  We do this by putting a throws FileNotFoundException on the declaration of main() (or whatever method we're in) public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File("input.txt")); public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File("input.txt"));

58  Unlike the command line, you should really close files when you're done reading from them  If you forget, it's okay: Java will automatically close them when your program quits  But, for situations where you're accessing multiple files, it may be important to close them Scanner in = new Scanner(new File("input.txt")); PrintWriter out = new PrintWriter(new FileOutputStream ("output.txt")); //do stuff in.close(); out.close(); Scanner in = new Scanner(new File("input.txt")); PrintWriter out = new PrintWriter(new FileOutputStream ("output.txt")); //do stuff in.close(); out.close();

59

60 Return type NameJob intlength() Find the length of the String charcharAt(int i) Give the char at index i (starting from 0) booleanequals(String s) Returns true if s contains exactly the same characters, false otherwise intcompareTo(String s) Returns a negative number if the String comes before s in the alphabet, a positive number if the String comes after s in the alphabet, and 0 if they are identical Stringsubstring(int a, int b) Returns the substring of the String that starts at index a and goes up to but does not include index b

61 Return typeNameJob doublesin( double theta ) Find the sine of angle theta doublecos( double theta ) Find the cosine of angle theta doubletan( double theta ) Find the tangent of angle theta doubleexp( double a ) Raise e to the power of a (e a ) doublelog( double a ) Find the natural log of a doublepow( double a, double b ) Raise a to the power of b (a b ) longround( double a ) Round a to the nearest integer doublerandom() Create a random number in [0, 1) doublesqrt( double a ) Find the square root of a

62 Return TypeMethodUse intnextInt() Read in the next int doublenextDouble() Read in the next double Stringnext() Read in the next String

63 Return TypeMethodUse voidline(double x0, double y0, double x1, double y1) Draw a line from (x0,y0) to (x1,y1) voidpoint(double x, double y) Draw a point at (x,y) voidcircle(double x, double y, double r) Draw a circle centered at (x,y) with radius r voidfilledCircle(double x, double y, double r) Draw a filled circle centered at (x,y) with radius r voidsquare(double x, double y, double r) Draw a square centered at (x,y) with edges 2r voidfilledSquare(double x, double y, double r) Draw a filled square centered at (x,y) with edges 2r voidsetPenColor(Color c) Start drawing with color c

64 Return Type MethodUse voidsetXscale(double x0, double x1) Set the x scale voidsetYscale(double y0, double y1) Set the y scale voidsetPenRadius(double r) Set the pen radius voidsetCanvasSize(int w, int h) Set canvas size voidclear() Clear canvas to white voidclear(Color c) Clear canvas to color c voidshow(int delay) Delay for delay ms

65 Return TypeMethodUse double[]read(String file) Read a WAV file into an array of double s void save(String file, double[] input) Save an array of double s (samples) into a WAV file voidplay(String file) Play a WAV file voidplay(double[] input) Play an array of double s (samples)

66 Return Type MethodUse Color(int r, int g, int b) Creates a new color with r, g, and b as the red, green, and blue values intgetRed() Get the red color component intgetGreen() Get the green color component intgetBlue() Get the blue color component

67 Return Type MethodUse Picture(String file) Creates a Picture from a file Picture(int w, int h) Create a blank Picture with width w and height h intwidth() Return the width of the image intheight() Return the height of the image Colorget(int i, int j) Return the Color of the pixel at ( i, j ) voidset(int i, int j, Color c) Set the Color of the pixel at ( i, j ) to c voidshow() Display the image voidsave(String file) Save the Picture to a file

68

69

70  There is no next time!

71  Finish Project 5!  Due tonight before midnight  Study for Final Exam  2:30 - 5:30pm, Thursday, 12/10/2015 (CS121B)  11:00am - 2:00pm, Monday, 12/07/2015 (CS121C)


Download ppt "Week 15 – Friday.  Student Questions  Review up to Exam 2  Loops  Arrays  StdDraw  StdAudio  Static methods."

Similar presentations


Ads by Google