1 / 28

BIT115: Introduction to Programming

BIT115: Introduction to Programming. Lecture 6a. Instructor: Craig Duckett. Assignments. Assignment 2. Assignment 2 is due THIS Wednesday, July 23 , by midnight. Assignment 1 Revision. Assignment 1 Revision is due Monday, July 28 , by midnight. Assignment 2 Revision.

bert
Download Presentation

BIT115: Introduction to Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. BIT115: Introduction to Programming Lecture 6a Instructor: Craig Duckett

  2. Assignments Assignment 2 • Assignment 2 is due THISWednesday, July 23, by midnight Assignment 1 Revision • Assignment 1 Revision is due Monday, July 28, by midnight Assignment 2 Revision • Assignment 2 Revision due Lecture 10, Monday, August 4th, by midnight Assignment 3 • Assignment 3 due Lecture 11, Wednesday, August 6th, by midnight

  3. But First… The Quiz!

  4. A Quick Look at What We've Learned So Far • Class that has the just the main method: • public class someName extends Object [class name has to match file name] • Class that holds Robot extension and the main method • public class someName extends Robot [class name has to match file name] • File that holds two classes, one for the constructor and methods, one for main • class someName extends Robot • public class otherName extends Object [class name has to match file name] • When using more than one class in a file, the CLASSES NEED DIFFERENT NAMES • SEE EXAMPLE COMPARISON ON NEXT SLIDE  • Constructor – lining up the new class with the super class • Methods – public void someMethod() • Curly Braces – Opening { and Closing } "Squiggles" properly indented • this keyword – a generic placeholder for whatever robot will be using the method • if statement, while statement, if…else statement • Trace and Debug Tables • Counters, including increment and decrement • +, -, <, <=, >, >=, ==, != • Robot methods: pickThing(), putThing(), move(), turnLeft(), frontisClear(), getDirection(), getStreet(), getAvenue(), canPickThing(), countThingsInBackpack(), • Output – System.out.print ("String"); or System.out.println("String"); • Java Library - import java.util.*; • Input – Scanner Keyboard = new Scanner(System.in); • hasNextInt(), nextInt(), nextLine()

  5. We are nearing the END of the FIRST HALFOF THE QUARTER --- • WHAT DOES THIS MEAN IN THE COSMIC SCHEME OF THINGS? In the SECOND HALF of the Quarter there will be: • Less Theory, More Hands-On Work (Less means Less, not No) • Less Hand-Holding, More Trial-and-Error • Less Explanation, More Research & Investigation, More Poking Around For Code, More “Googling It” and More(on occassion) Aggravation. Grrrr! • When You Do Get Aggravated: Remember to STEP AWAY from your code occasionally, take a break, walk around, go and eat, contemplate the great outdoors, then come back. If it is late at night, go to bed. You may discover that bizarre thing that sometimes can happen, where you DREAM IN CODE, and wake up in the morning refreshed and with the beginnings of a solution!

  6. What We're Going Over Today • Today we're going to have a closer look at parametersand arguments • We're going to look at "instance variables" • You should have enough coding behind you by the end of the lecture today to successfully complete the navigational part of the Maze (i.e., to move through the Maze from start to finish using logic) • After the lecture on "instance variables" you should have the coding wherewithal to set up the counters and be able to collect the number of moves made, how many times the robot moved in any particular direction, and then print out the whole shebang at the end of the program.

  7. More Flexible Methods

  8. More Flexible Methods The Way We Originally Learned (“Hard Coded”) public void move2() { this.move(); this.move(); } public void move3() { this.move(); this.move(); this.move(); } public void move4() { this.move(); this.move(); this.move(); this.move(); } A More Flexible Way (“Argument Coded”) public void howManyMoves(int numMoves) { int counter = 0; while(counter < numMoves) { this.move(); counter++; } // Note: This method has no error handling }  New Flexible Method karel.howManyMoves(2); karel.howManyMoves(3); karel.howManyMoves(4); karel.howManyMoves(12); How it might be called in main  or  or  or 

  9. Chapter 4.6: Using Parameters You’ll notice that every new method (service) we’ve created does something: Each time we call upon one of those services, it’ll always do the same thing • We could have asked for user input, but • then the service would fill TWOroles • Doing <something> • Interacting with the user • We'd like each service to have a single, well-defined, and easy to summarizerole • Thus, things like moveMultipleshould move the robot through multiple intersections • Things like main should run the part of the program that relays instructions from the user to the robot(s) public void turnAround() { this.turnLeft(); this.turnLeft(); } public void move3() { this.move(); this.move(); this.move(); } public void turnRight() { this.turnAround(); this.turnLeft(); }

  10. Chapter 4.6: Using Parameters We need a way to pass information to a service. We’d like to be able to say: rob.moveMultiple(3); or rob.moveMultiple(7); or even Scanner keyboard = new Scanner(System.in); int howFar = keyboard.nextInt(); rob.moveMultiple(howFar); The actual info being passed to the service is called an ARGUMENT The service must also be told to expect this information ANDmake room for it to be stored somewhere in memory, so instead of: public void moveMultiple() we'll write public void moveMultiple(intnumberOfIntersections)

  11. Chapter 4.6: Using Parameters For integers ints, this creates (within moveMultiple) a COPY of whatever we put inside the parentheses in main. Inside of moveMultiple, numberOfIntersections behaves just like any other int variable. We can print it out, assign new values to it, use it in a while loop, etc. The thing that tells the method service to expect some info is called a PARAMETER. Of course we’ve been doing this all along whenever we’ve been declaring a new instance of a Robot.

  12. Chapter 4.6: Using Parameters Notice how the parameters that we declare are matched up against the “hard-coded” arguments that we give it: importbecker.robots.*; public class MrRobotoextends Robot { publicMrRoboto(City theCity, intstreet, intavenue, Direction aDirection) { super(theCity, street, avenue, aDirection); } public void turnAround() { this.turnLeft(); this.turnLeft(); } public static void main(String[] args) { City bothell = new City(); MrRobotolisa = newMrRoboto(bothell, 3, 2, Direction.SOUTH); lisa.turnAround(); lisa.move(); lisa.turnAround(); } } These, in turn, are passed through the superclass constructor.

  13. Chapter 4.6: Using Parameters Suppose we want a subclass of Robot that can easily tell us if it has gone past a particular Avenue, for example Avenue 18... We could use a getAvenuemethod and “hard-code” compare it to 18: if(this.isPastAvenue == 18) {// what to do when the robot has strayed too far} but our code is more self-documenting with a predicate: if(this.isPastAvenue(18)) // The coder supplies 18 here {// what to do when the robot has strayed too far} // or better yet: if(this.isPastAvenue(anAvenue)) // The user supplies 18, or 22, or 66, etc. // using the Scanner class and System.in input {// what to do when the robot has strayed too far} TheisPastAvenuemethod is written as follows: private booleanisPastAvenue(intanAvenue) // either way this is used { returnthis.getAvenue()> anAvenue; // the same and with any } // number being entered In main you’d call it this way: this.isPastAvenue(anAvenue);

  14. Using a While Statement with a Parameter The following method moves a robot east to Avenue 18. public void moveToAvenue18() // <-- no parameter { while(this.getAvenue() < 18) { this.move(); } } This is very limited, and only useful to move the robot specifically to Avenue 18 since it was “hard-coded” to do so. With a parameter, however, it can be used to move the robot to any avenue east of its current location. public void moveToAvenue(intdestAve) // with parameter { while(this.getAvenue() < destAve) { this.move(); } } In main you’d call it this way: this.moveToAvenue(18); In main you’d call it this way: this.moveToAvenue(destAve);

  15. Chapter 6.2.2: Reviewing Parameter Variables In this section, we will show how parameter variables are closely related to temporary variables, explore using parameters with constructors, and discuss overloading. Parameter Variables versus Temporary Variables public void moveTheBot() { int howFar = 2; // <-- temporary variable this.street = this.street + howFar; } In main you’d call it this way: this.moveTheBot(); public void moveTheBot(int howFar) // <-- parameter variable { this.street = this.street + howFar; } In main you’d call it this way: this.moveTheBot(howFar); In main you’d call it this way: this.moveTheBot(2);

  16. EXAMPLE Method Without a Parameter Argument public void moveMultiple(){this.move();this.move(); this.move(); this.move(); this.move(); } Main rob.moveMultiple(); // rob will move 5 times

  17. EXAMPLE Method Without a Parameter Argument public void moveMultiple(){intcounter = 0;while( counter < 5) { if(this.frontIsClear()) {this.move();counter = counter + 1; // This is the same as counter++;} } } Main rob.moveMultiple(); // rob will move 5 times

  18. EXAMPLE Method Without a Parameter Argument public void moveMultiple(){intcounter = 0;while( counter < 5) // 5 is “hard-coded” here, so easier to change at{ // this coded location but there is a better solution if(this.frontIsClear()) {this.move();counter = counter + 1; } } } Main rob.moveMultiple(); // rob will move 5 times, and only 5 times

  19. EXAMPLE Method with Parameter Argument public void moveMultiple(intnumberOfIntersections) // declare and add argument{intcounter = 0;while( counter < numberOfIntersections) // replace 5 with that argument { if(this.frontIsClear()) {this.move(); counter = counter + 1;} } } Main • rob.moveMultiple(5); // <-- 5 is placed within the method call as an argument • // The 5 is still being “hard-coded” but this time as a parameter argument • // instead of an integer defined inside the method. This makes it easier since • // different numbers can now be called when the method is used, but why not // free up the method to call up ANY input actually entered by the user? That • // way no number is being “hard-coded” before the program is compiled and run

  20. EXAMPLE Method with Parameter Argument public void moveMultiple(intnumberOfIntersections) // declare and add argument{intcounter = 0;while( counter < numberOfIntersections) // replace 5 with that argument { if(this.frontIsClear()) {this.move(); counter = counter + 1;} } } Main System.out.println("How many intersections forward would you like the robot to go?");if( keyboard.hasNextInt()) // hasNextInt checks the input is an integer {intnumMoves = keyboard.nextInt(); // nextIntputs it into memory containerSystem.out.println ("You entered a " + numMoves + "."); // called numMovesthis.moveMultiple(numMoves); } LET’S HAVE A CLOSER LOOK 

  21. EXAMPLE Method public void moveMultiple(intnumberOfIntersections){intcounter = 0;while( counter < numberOfIntersections) { if(this.frontIsClear()) {this.move(); counter = counter + 1;} } } numberOfIntersections Main System.out.println("How many intersections forward would you like the robot to go?");if( keyboard.hasNextInt() ) {intnumMoves = keyboard.nextInt(); System.out.println ("You entered a " + numMoves + ".");this.moveMultiple(numMoves); }

  22. EXAMPLE Method public void moveMultiple(intnumberOfIntersections){intcounter = 0;while( counter < numberOfIntersections) { if(this.frontIsClear()) {this.move(); counter = counter + 1;} } } numberOfIntersections Main numMoves System.out.println("How many intersections forward would you like the robot to go?");if( keyboard.hasNextInt() ) {intnumMoves= keyboard.nextInt(); System.out.println ("You entered a " + numMoves + ".");this.moveMultiple(numMoves); }

  23. EXAMPLE Method public void moveMultiple(intnumberOfIntersections){intcounter = 0;while( counter < numberOfIntersections) { if(this.frontIsClear()) {this.move(); counter = counter + 1;} } } numberOfIntersections 5 Main numMoves System.out.println("How many intersections forward would you like the robot to go?");if( keyboard.hasNextInt() ) {intnumMoves= keyboard.nextInt(); System.out.println ("You entered a " + numMoves+ ".");this.moveMultiple(numMoves); }

  24. EXAMPLE Method public void moveMultiple(intnumberOfIntersections){intcounter = 0;while( counter < numberOfIntersections) { if(this.frontIsClear()) {this.move(); counter = counter + 1;} } } numberOfIntersections 5 Main numMoves System.out.println("How many intersections forward would you like the robot to go?");if( keyboard.hasNextInt() ) {intnumMoves= keyboard.nextInt(); // nextInt actually gets the inputSystem.out.println ("You entered a " + numMoves+ ".");this.moveMultiple(numMoves); }

  25. EXAMPLE Method 5 public void moveMultiple(intnumberOfIntersections){intcounter = 0;while( counter < numberOfIntersections) { if(this.frontIsClear()) {this.move(); counter = counter + 1;} } } numberOfIntersections 5 Main numMoves System.out.println("How many intersections forward would you like the robot to go?");if( keyboard.hasNextInt() ) {intnumMoves = keyboard.nextInt(); System.out.println ("You entered a " + numMoves + ".");this.moveMultiple(numMoves); }

  26. Chapter 6.2.2: Method Overloading In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java implements polymorphism. Polymorphism is the ability of an object to take on many forms, and uses the “is a” test determine multiple inheritancethrough from different classes, subclasses, etc. Method overloading is one of Java's most exciting and useful features. When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. Thus, overloaded methods must differ in the type and/or number of their parameters. While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method. When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call. Let’s have a look-see - - -

  27. Method Overloading public class MethodOverloading extends Object {public void test(int a) { System.out.println("a: " + a); } public void test(int a, intb) { System.out.println("a and b: " + a + "," + b); } public double test(double a) { System.out.println("double a: " + a);returna*a; }public static void main(String args[]) { MethodOverloading MethodOverloading = new MethodOverloading();doubleresult; MethodOverloading.test(10); MethodOverloading.test(10, 20); result = MethodOverloading.test(5.5); System.out.println("Result : " + result); }} a: 10 a and b: 10, 20 double a: 5.5 Result: 30.25

More Related