Lecture 7 Instructor: Craig Duckett Assignment 2 DUE TONIGHT! Uploaded to StudentTracker by midnight I’ve already graded and returned about 1/3 of the class Assignment 1 Revision DUE Monday, August 1st Assignment 2 Revision DUE Monday, August 8th Assignment Dates (By Due Date) • Assignment 2 (LECTURE 7) Wednesday, July 27th The Fickle Finger of Fate • Assignment 1 Revision (LECTURE 8) Monday, August 1st • Assignment 2 Revision (LECTURE 10) • • • • Monday, August 8th Assignment 3 (LECTURE 11) Wednesday, August 10th Assignment 3 Revision (LECTURE 13) Wednesday, August 17th Assignment 4 (LECTURE 15) Wednesday, August 24th EXTRA CREDIT (LECTURE 25) Wednesday, August 24th 3 But First... ... The Warm-Up Quiz By-Passing/Jumping BIT116 BIT142 BIT 115 (Intro to Programming) BIT 116 (JavaScript) BIT 142 (Intermediate Programming C#) BIT 143 (Data Structures) Required to transfer to UW SKIP BIT 116? • Solid performance in this class: On pace to earn a 3.8 GPA or higher. • Very comfortable and confident with this material • Feel like you can handle more at a faster right. • Contact Mike Panitz the Instructor of BIT142 via email ( mpanitz@cascadia.edu ) and CC me ( cduckett@Cascadia.edu ) to make a request to jump into BIT142 from BIT115 (explaining why you think you are a good candidate to do this). • Once I receive your email, I will email Mike Panitz in private giving him my yea or nay as to whether I think you are a good candidate to make the jump. Once Mike hears from me he will then contact you with instructions how to take a PLACEMENT QUIZ to be sent out on TBA (1-4 exercises) which you will have to pass before you can register for BIT142 (you will have to print out the email you receive from Mike and register in-person at Kodiak. You cannot do this on-line, since it requires special permission). Today’s Topics • Overriding Inherited Methods Using super. • Debugging Using System.out • Random Numbers • Multiple Files Some Quick Refreshers! Variables: Quick Refresher Declaring a variable creates a named storage location in memory large enough to hold a value of a particular type. For instance, if you declare a variable int num, then you are saying you need a storage location in memory named num that will be large enough to hold an integer (any number in the range of -2,147,483,648 and 2,147,483,647 that takes up a total of 32-bits of storage space). int num; num “Initializing the variable” simply means that you are putting an initial value in that named storage location: int num = 0; int num = 0; 0 num Now, using code in your program you can access the value that is stored in that named storage location, or add to it, or subtract from it, or alter it in some other way, since it is a variable (meaning that it can be changed and it doesn’t have to remain the same, i.e., it isn’t constant). System.out.print("The storage container called num contains a " + num); Counter: Quick Refresher Setting up a counter creates a named storage location in memory large enough to hold a value of a particular type. Counters are useful when working with loops. int counter = 0; 0 counter while(counter < 3) { move(); System.out.println("Counter is " + counter); counter = counter + 1; // Or counter++; } 1 counter 2 counter 3 counter Instance Variables: Refresher An instance variable is a variable that is declared and initialized inside a class, but outside of the methods. A variable declared inside a method is a local or temporary variable and can only be used by that method, but a global or instance variable declared outside of a method can be used by any of the methods or objects of that class. Local or Temporary Variables Only Local Variables AND Instance Variable Overriding Inherited Methods Inheritance: Quick Refresher import becker.robots.*; public class MrRoboto extends Robot { // Construct a new MrRoboto public MrRoboto(City theCity, int street, int avenue, Direction aDirection) { super(theCity, street, avenue, aDirection); } public void turnAround() { this.turnLeft(); this.turnLeft(); } public void move3() { this.move(); this.move(); this.move(); } public void turnRight() { this.turnAround(); this.turnLeft(); } } Overriding Inherited Methods Java allows us to override methods inherited from the superclass using the super. (‘super dot’) keyword in the method. Both the original method and the overriding method must: • have the same name • declare the same data type • accept same number of parameters • return the same data type (we’ll be going over return in the next lecture) See: ICE_10_Demo_1.java // DEMO 1: Overriding the turnLeft() method /////////////////////////////////////////////////////////////////// import becker.robots.*; class SpinningRobot extends Robot { SpinningRobot ( City c, int st, int ave, Direction dir, int num) { super(c, st, ave, dir, num); } public void turnLeft() { super.turnLeft(); // super.turnLeft(); // super.turnLeft(); // super.turnLeft(); // super.turnLeft(); // } super here tells compiler to use turnLeft() from the super class Robot and not from its own class SpinningRobot. If we would have used a ‘this’ here instead of ‘super’ then we would find ourselves in an infinite loop } public class ICE_10_Demo_1 extends Object { public static void main(String[] args) { City Dizzyland = new City(10, 10); SpinningRobot mary = new SpinningRobot(Dizzyland, 4, 4, Direction.EAST, 0); mary.turnLeft(); // mary turns left 5 times } } Class Sub-Class Sub-Sub-Class Sub-Sub-Sub-Class … class MrRoboto extends Robot { MrRoboto( City c, int st, int ave, Direction dir, int num) { super(c, st, ave, dir, num); } <<methods here>> } class NeuvoRoboto extends MrRoboto { NeuvoRoboto( City c, int st, int ave, Direction dir, int num) { super(c, st, ave, dir, num); } <<methods here>> } See: ICE_10_Demo_2.java Overloading Overriding Same method name Different parameter Same method name Same parameter Robot class: move( ); RobotSE class: move(int howFar); Robot class: turnLeft( ); MrRoboto class: turnLeft( ); ICE: Overriding Inherited Methods As always, we’ll wait until the end of the LECTURE to do all the ICEs together Debugging Programmatically Debugging: A Brief Look Using System.out for debugging In a method: System.out.println(this); With an object (for example, a Robot object named rigby): System.out.println(rigby); [street=1, avenue=4, direction=EAST, isBroken=false, numThingsInBackpack=3] With an object (for example, a Thing object named t1): System.out.printlin(t1); [street=1, avenue=4] DebugExample.java Random Numbers Random Numbers Depending on your program, sometimes it useful to be able to generate a random number (or numbers) that can be used to interact with your code to accomplish various tasks: • Simple Gaming (spin the wheel, roulette, craps, etc) • Advanced Gaming (from what coordinate locations the zombies will attack, where the artillery strike will hit, how much schrapnel will fly, the direction and amount of smoke in the wind, etc) • Statistical Sampling (political affiliation, voter turnout, employment / unemployment numbers, etc) • Computer Simulation (predicting earthquakes, paths of hurricanes, tide flows, etc) • Cryptography (codes and encryption) • Completely Randomized Design (nuissance variables, response variables) Text Random Numbers Java has a rich toolkit for generating random numbers, in a class named Random. Random can generate many kinds of random numbers, but we’ll won’t going into these in this introduction. For more information, see http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Random.html Random is defined in the "java.util" library package, so any Java source file that uses Random must begin with a line of the form: import java.util.Random; or import java.util.*; The easiest way to initialize a random number generator is to use the parameterless constructor, for example: Random generator = new Random(); Random as it stands is NOT truly random. An instance of the Random class is used to generate a stream of pseudo random numbers using a 48-bit seed, which is modified using a linear congruential formula: xi+1 = (0x5DEECE66DL * xi + 11) mod 248 - 1 If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. Java implementations for Random have been developed this way for the sake of absolute portability of Java code. However, subclasses of Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods. Example: you can develop a subclass algorithm for Random that interacts with its seed in some way (through multiplication, division, a bit of both) like using the current system time from your computer (e.g., total seconds from some predefined date or randomized date). Some applications will find the random method in class Math (Math.random) simpler to use, as it creates a pseudorandom double greater than or equal to 0.0 and less than 1.0. Multiple Program Files Multiple Files (Programs) Separating main from classes to create more manageable code • a main file • one or more class files • an optional .txt text file for configuration, additional input, or output (like creating a log file) Things to remember when dealing with multiple .java files: • • • class name must match file name All files must be grouped together in the same area (folder, directory, desktop, drive, etc.) jGrasp automatically saves any changes made in the class files when compiling main, but I would get in the habit of recompiling all class files first before compiling main since other compilers behave differently. SINGLE FILE | STYLE 1 import becker.robots.*; public class MrRoboto extends Robot { public MrRoboto(City theCity, int avenue, int street, Direction aDirection) { super(theCity, avenue, street, aDirection); } public void turnAround() { this.turnLeft(); this.turnLeft(); } public void move3() { this.move(); this.move(); this.move(); } public void turnRight() { this.turnAround(); this.turnLeft(); } In this style, since there is only one class name, then: the class name MrRoboto, the constructor name MrRoboto, and the file name MrRoboto must all be the same. public static void main(String[] args) { City bothell = new City(); MrRoboto lisa = new MrRoboto(bothell, 3, 2, Direction.SOUTH); lisa.move3(); lisa.turnRight(); lisa.move3(); lisa.turnAround(); } } SINGLE FILE | STYLE 2 import becker.robots.*; class MrRoboto extends Robot { // Construct a new MrRoboto public MrRoboto(City theCity, int avenue, int street, Direction aDirection) { super(theCity, avenue, street, aDirection); } public void turnAround() { this.turnLeft(); this.turnLeft(); } public void move3() { this.move(); this.move(); this.move(); } public void turnRight() { this.turnAround(); this.turnLeft(); } In this style, since there are two class names, then the file name must match the class name that contains the main method, MrRobotoMain. Also the class that holds the constructor and the new methods only starts with class, and the constructor starts with public. The class that holds main must start with public class } public class MrRobotoMain extends Object { public static void main(String[] args) { City bothell = new City(); MrRoboto lisa = new MrRoboto(bothell, 3, 2, Direction.SOUTH); lisa.move3(); lisa.turnRight(); lisa.move3(); lisa.turnAround(); } } Splitting MrRobotoMain.java into Two Files METHODS and MAIN: 1 File with 2 Classes METHODS: 1 File with 1 Class MAIN: 1 File with 1 Class import becker.robots.*; Needs its own ‘import’ statement MrRoboto.java class MrRoboto extends Robot { // Construct a new MrRoboto public MrRoboto(City theCity, int avenue, int street, Direction aDirection) { super(theCity, avenue, street, aDirection); } public void turnAround() { this.turnLeft(); this.turnLeft(); } public void move3() { this.move(); this.move(); this.move(); } public void turnRight() { this.turnAround(); this.turnLeft(); } In this case, since there are two files, then the class names must match the files names, and both files must be in the same folder/directory. Each file needs to include the line import becker.robots.*; as well. } SPLIT IN TWO MrRobotoMan.java import becker.robots.*; Needs its own ‘import’ statement public class MrRobotoMain extends Object { public static void main(String[] args) { City bothell = new City(); MrRoboto lisa = new MrRoboto(bothell, 3, 2, Direction.SOUTH); lisa.move3(); lisa.turnRight(); lisa.move3(); lisa.turnAround(); } } Always compile the file that contains main when working with multiple files, since you cannot compile a file that does not contain main Multiple Files Go in Same Folder/Directory The files need to be able “find” each other to work correctly, so storing them in the same directory or folder greatly simplifies this discovery process. MrRoboto.java THE METHOD FILE MrRobotoMain.java THE MAIN FILE NOW A DEMONSTRATION Using MrRobotoMain.java Assignment 3 Final Hint With Pseudo-Code public void NavigateMaze() { while(!this.isAtEndSpot() ) { // Something happens here // Something happens here // Something happens here // if robot can not pick up a thing { // if robot still has things in its backpack { // put down a thing } } NESTED IF STATEMENTS There is an if statement INSIDE an if statement // Something happens here } // print everything here } See MAZE city next slide for demonstration Mid-Term Review • Pencil and Paper Only…I’ll supply the paper • 150 Points | Worth 15% of Overall Grade • 150 Total Points • 6 - True/False Questions (6 x 5 points = 30 points) • 8 - Multiple Choice Questions (8 x 5 points = 40 points) • 2 - Traces ( 2 x 20 points = 40 points) • 1 - Writing Code Section ( 1 x 20 points = 20 points) • 1 - Finding Errors Section (1 x 20 points = 20 points) • Mid-Term Study Guide is available on BIT115 website ICE: Overriding Inherited Methods ICE: Multiple File Programs Do both sets of ICEs now… NOTE: ALWAYS download your multiple files from the website first and then work on them and run them from the same directory, or else things aren’t going to work correctly. NOTE: If you want to read how I constructed a City using a separate .txt file, please refer to the Becker Robot Library > becker.robots > City and scroll down to the Constructor Detail on the right-hand side (the section begins with “Construct a new city by reading information to construct it from a file…”