Download presentation
Presentation is loading. Please wait.
Published byBarry Cain Modified over 9 years ago
1
Lecture 11 Instructor: Craig Duckett
2
Announcements Assignment 1 Revision DUE TONIGHT February 10 th In StudentTracker by midnight If you have not yet submitted an Assignment 1, this is your last chance to do so to earn points, otherwise you will get a zero, and I really dislike handing out zeros! NO CLASSES ON MONDAY, FEBRUARY 15 th ! College Closed! College Closed! Presidents’ Day!
3
3 Assignment 2 GRADED! RETURNED! WOOT! WOOT! Assignment 1 Revision (LECTURE 11) DUE TONIGHT ! Wednesday, February 10 Assignment 2 Revision (LECTURE 12) Wednesday, February 17 Assignment 3 (LECTURE 13) Monday, February 22 Assignment 3 Revision (LECTURE 16) Wednesday, March 2 Assignment 4 (LECTURE 19) Monday, March 14 NO REVISION Extra Credit 01 (LECTURE 20) Wednesday, March 16 Assignment Dates (By Due Date)
4
But First… The Quiz! The Quiz! Mid-Term Post-Mortem
5
TODAY BEGINS THE SECOND HALF OF THE QUARTER -- WHAT DOES THIS MEAN IN THE COSMIC SCHEME OF THINGS? 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!
7
INPUT: Scanner Class REVIEW nextInt() Assumes there is an int and does something with it hasNextInt() Checks to see if there is an int (boolean true or false) nextLine() Replaces the int in the keyboard buffer with a newline character (Enter) so the program won't use the int again import java.util.Scanner; or import java.util.*; Scanner keyboard = new Scanner(System.in);
8
Input Scanner The Scanner Class To read input from the keyboard we use the Scanner class. Like Random, the Scanner class is defined in the Java Library package called java.util, so we must add the following statement at the top of our programs that require input from the user: import java.util.*; // <-- I usually do this or import java.util.Scanner; https://docs.oracle.com/javase/7/docs/api/java/util/package-summary.html
9
The Scanner Class Scanner objects work with System.in To create a Scanner object: Scanner keyboard = new Scanner(System.in); NOTE: Like any other object, keyboard here is just a name “made up” by the coder and can be called anything instead—input, feedIine, keyIn, data, stuffComingFromTheUser, etc.—although it should represent a word most apt to its purpose. In this case I am using the name keyboard since it seems apt as I’ll be using the keyboard to enter data (i.e., do the input)
10
New Scanner Methods These are for ints (integers). There are also Scanner methods available for floats, etc, which we'll see later on in the quarter nextInt() Assumes there is an int and does something with it hasNextInt() Checks to see if there is an int (boolean true or false) nextLine() Replaces the int in the keyboard buffer with a newline character (Enter) so the program won't use the int again Okay: Let's have a look at the Basic_Keyboard_IO.java program from the previous lecture
11
What We're Going Over Today Today we're going to have a closer look at parameters and arguments We're also going to look at instance variables You should have enough coding behind you by the end of the lecture today to successfully complete the coding for Assignment 3 “The Maze”: Successfully Navigate through the Maze from start to finish using various logic Use "instance variables" 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 various totals at the end of the program.
12
More Flexible Methods
13
The Way We Originally Learned (“Hard Coded”) public void move2() { this.move(); this.move(); } A More Flexible Way (“Argument Coded”) karel.howManyMoves(2); karel.howManyMoves(3); karel.howManyMoves(4); karel.howManyMoves(12); public void howManyMoves(int numMoves) { int counter = 0; while(counter < numMoves) { this.move(); counter++; } // Note: This method has no error handling } New Flexible Method How it might be called in main or public void move3() { this.move(); this.move(); } public void move4() { this.move(); this.move(); }
14
Argument, Pass, Parameter
15
Chapter 4.6 Chapter 4.6: Using Parameters You’ll notice that every new method (service) we’ve created does something: public void turnAround() { this.turnLeft(); this.turnLeft(); } public void move3() { this.move(); this.move(); } public void turnRight() { this.turnAround(); this.turnLeft(); } 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 TWO roles 1.Doing 2.Interacting with the user We'd like each service to have a single, well- defined, and easy to summarize role Thus, things like moveMultiple should 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)
16
Chapter 4.6 Chapter 4.6: Using Parameters We need a way to pass information to a method or service. rob.moveMultiple(3); or rob.moveMultiple(7); or even Scanner keyboard = new Scanner(System.in); int howFar = keyboard.nextInt(); rob.moveMultiple(howFar); We’d like to be able to say: The actual info being passed to the method is called an ARGUMENT The method must also be told to expect this information AND make room for it to be stored somewhere in memory, so instead of: public void moveMultiple() we'll write public void moveMultiple(int someNumber)
17
Chapter 4.6 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 the moveMultiple() method someNumber 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. Let’s have a look how this works…
18
Arguments and Parameters A method in new class up top: public void moveMultiple(int moves) { int counter = 0; while(counter < moves) { move(); counter++; } In main below: Scanner keyboard = new Scanner(System.in); int howFar = keyboard.nextInt(); rob.moveMultiple(howFar); ARGUMENT PARAMETER counter moves howFar PASS
19
Chapter 4.6 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 getAvenue method 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} The isPastAvenue method is written as follows: private boolean isPastAvenue(int anAvenue) // either way this is used { return this.getAvenue() > anAvenue; // the same and with any } // number being entered In main you’d call it this way: this.isPastAvenue(anAvenue );
20
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(int destAve) // 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);
21
Chapter 6.2.2 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. public void moveTheBot() { int howFar = 2; // <-- temporary variable this.street = this.street + howFar; } Parameter Variables versus Temporary Variables public void moveTheBot(int howFar) // <-- parameter variable { this.street = this.street + howFar; } In main you’d call it this way: this.moveTheBot(); In main you’d call it this way: this.moveTheBot(2); In main you’d call it this way: this.moveTheBot(howFar);
22
public void moveMultiple() { this.move(); this.move(); this.move(); this.move(); } rob.moveMultiple(); // rob will move 5 times EXAMPLE Method Without a Parameter Argument Main
23
public void moveMultiple() { int counter = 0; while( counter < 5) { if(this.frontIsClear()) { this.move(); counter = counter + 1; // This is the same as counter++; } } rob.moveMultiple(); // rob will move 5 times EXAMPLE Method Without a Parameter Argument Main
24
public void moveMultiple() { int counter = 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; } } rob.moveMultiple(); // rob will move 5 times, and only 5 times EXAMPLE Method Without a Parameter Argument Main
25
public void moveMultiple(int numberOfIntersections) // declare and add argument { int counter = 0; while( counter < numberOfIntersections) // replace 5 with that argument { if(this.frontIsClear()) { this.move(); counter = counter + 1; } } 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 EXAMPLE Method with Parameter Argument Main
26
public void moveMultiple(int numberOfIntersections) // declare and add argument { int counter = 0; while( counter < numberOfIntersections) // replace 5 with that argument { if(this.frontIsClear()) { this.move(); counter = counter + 1; } } System.out.println("How many intersections forward would you like the robot to go?"); if( keyboard.hasNextInt()) // hasNextInt checks the input is an integer { int numMoves = keyboard.nextInt(); // nextInt puts it into memory container System.out.println ("You entered a " + numMoves + "."); // called numMoves this.moveMultiple(numMoves); } EXAMPLE Method with Parameter Argument Main LET’S HAVE A CLOSER LOOK
27
public void moveMultiple(int numberOfIntersections) { int counter = 0; while( counter < numberOfIntersections) { if(this.frontIsClear()) { this.move(); counter = counter + 1; } } System.out.println("How many intersections forward would you like the robot to go?"); if( keyboard.hasNextInt() ) { int numMoves = keyboard.nextInt(); System.out.println ("You entered a " + numMoves + "."); this.moveMultiple(numMoves); } EXAMPLE Method Main numberOfIntersections counter 0
28
public void moveMultiple(int numberOfIntersections) { int counter = 0; while( counter < numberOfIntersections) { if(this.frontIsClear()) { this.move(); counter = counter + 1; } } System.out.println("How many intersections forward would you like the robot to go?"); if( keyboard.hasNextInt() ) { int numMoves = keyboard.nextInt(); System.out.println ("You entered a " + numMoves + "."); this.moveMultiple(numMoves); } EXAMPLE Method Main numMoves numberOfIntersections counter 0
29
public void moveMultiple(int numberOfIntersections) { int counter = 0; while( counter < numberOfIntersections) { if(this.frontIsClear()) { this.move(); counter = counter + 1; } } System.out.println("How many intersections forward would you like the robot to go?"); if( keyboard.hasNextInt() ) { int numMoves = keyboard.nextInt(); System.out.println ("You entered a " + numMoves + "."); this.moveMultiple(numMoves); } EXAMPLE Method Main numberOfIntersections numMoves 5 counter 0
30
public void moveMultiple(int numberOfIntersections) { int counter = 0; while( counter < numberOfIntersections) { if(this.frontIsClear()) { this.move(); counter = counter + 1; } } System.out.println("How many intersections forward would you like the robot to go?"); if( keyboard.hasNextInt() ) { int numMoves = keyboard.nextInt(); // nextInt actually gets the input System.out.println ("You entered a " + numMoves + "."); this.moveMultiple(numMoves); } EXAMPLE Method Main numberOfIntersections numMoves 5 counter 0
31
public void moveMultiple(int numberOfIntersections) { int counter = 0; while( counter < numberOfIntersections) { if(this.frontIsClear()) { this.move(); counter = counter + 1; } } System.out.println("How many intersections forward would you like the robot to go?"); if( keyboard.hasNextInt() ) { int numMoves = keyboard.nextInt(); System.out.println ("You entered a " + numMoves + "."); this.moveMultiple(numMoves); } EXAMPLE Method Main numMoves numberOfIntersections 5 5 counter 0
32
Method Overloading Test() Test(int x) Test(int x, int y)
33
Chapter 6.2.2 Chapter 6.2.2: 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 inheritance through 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 - - -
34
Overloading public class MethodOverloading extends Object { public void test(int a) { System.out.println("a: " + a); } public void test(int a, int b) { System.out.println("a and b: " + a + "," + b); } public double test(double a) { System.out.println("double a: " + a); return a*a; } public static void main(String args[]) { MethodOverloading MethodOverloading = new MethodOverloading(); double result; 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
35
Instance Variables
36
Temporary/Local Variables versus Instance Variables All the local variables we've looked at so far will disappear at the end of the service. This means that they're temporary. We want memory that won't go away between service calls. We want the robot to remember something, to be able to keep a running tally that can be called up outside the scope of the method, not just get some temporary working space. An instance variable is what we need. A temporary variable can only be used inside the method where it is created. An instance variable may be used anywhere in the class containing it, by any of its methods. Remember: inside the class, but outside the methods and constructor. We manage this by declaring it private, which is foreshadowing the beginnings of encapsulation (although we aren’t quite there yet)
37
Temporary Variables Suppose we want to recall a number from one method to use in a different method? With local (or temporary) variables we can’t do that since the variable space is no longer available once we leave the method This does not work as planned because int x and int y are not available to Method3 So how do we get around this limitation of local variables?
38
Instance Variables We Do It With Instance Variables We declare the variables inside the class but outside the methods, that way all the methods can access and use them We also declare them as private so only objects instantiated from the class that declared them can use and/or alter them, protecting them from outside interference (hence, private).
39
Instance Variables We Do It With Instance Variables We declare the variables inside the class but outside the methods, that way all the methods can access and use them See: InstVar_Demo_1.java InstVar_Demo_2.java
40
Adding Another Argument to Constructor Useful when you create a new robot Object with other functionality besides just its placement in the City Let’s say you want to create a new type of Robot that also starts with a limited number of actions it’s allowed to do when the program is run, say for example, 20 total actions. You can add another argument to its constructor parameters to hold this number (although you’ll still have to write the code to actually do something with this number)! So, how would you do this? You would create a new class that extends the Robot class You could create an instance variable to hold data You could create a new argument in the constructor’s parameter to enter this additional data You could assign this entered data inside the constructor to the instance variable to be used elsewhere in the program for whatever purposes you need. In main, you would have your new robot object do something with this new number (either subtract from it or add to it) Example on Next Page
41
class RechargableRobot extends Robot { private int numOfActions; // number of actions executed instance-variable private int maxNumOfActions; // max number of actions instance-variable RechargableRobot( City c, int st, int ave, Direction dir, int num, int numActions) { super(c, st, ave, dir, num); // Notice NO additional argument here for the superclass this.maxNumOfActions = numActions; // set the max number of actions } // Additional Methods go here } public class ExampleNewArgument extends Object { public static void main(String[] args) { City toronto = new City(); RechargableRobot Jo = new RechargableRobot(toronto, 3, 0, Direction.EAST, 0, 20); new Thing(toronto, 3, 2); // Additional Code goes here } ExampleNewArgument.java
42
And Now, For Your Coding Pleasure …
43
HINT #1: This assignment is using RobotSE which contains additional methods that can be used in the code for this assignment. For example: turnRight(), turnaround(), isfacingEast(), isFacingSouth(), isFacingWest(), isFacingNorth(), etc. See the Becker Library for reference.Becker Library HINT #2: You will need to declare and initialize five (5) instance variables! These will be used to keep a running tally of the following: - Total Number of Moves Made - Total Number of Moves East - Total Number of Moves South - Total Number of Moves West - Total Number of Moves North HINT #3: You should create a method (e.g., movesCounted()) that will first keep a running tally of all the moves mentioned above and then move(). EXAMPLE: if the robot is facing east, tally move. HINT #4: You should create a method (e.g., printEverything()) that will print out the tally of all the moves made at the end of the NavigateMaze() method. HINT #5: Instead of using move() in the NavigateMaze() method, use movesCounted() which will not only move, but tally the move to the instance variables. HINT #6: All you need to add to the NavigateMaze() method to successfully navigate the Maze is fourteen (14) lines of code—and this includes the squiggles! If you need to use more lines with your logic, that’s okay too (it doesn’t only have to be 14). Also, the robot will only put down a thing if there is a thing in the backpack to put down, otherwise will still move without putting down a thing. HINT #7: Make sure and add backpack items to the robot object, don, down in main! Changing the 0 to at least 100 would be nice (I will be testing your code with 100 items in backpack, and 33, and 10, and 0). Some Helpful Hints for Assignment 3 Maze.java
44
class MazeBot extends RobotSE // <-- NOTE This is RobotSE class, not Robot class { public MazeBot(City theCity, int str, int ave, Direction dir, int numThings) { super(theCity, str, ave, dir, numThings); } // Five (5) Instance variables are declared and initialized here public void movesCounted() { //First tally the move and direction faced, then actually move } public void printEverything() { // Print everything (moves and directions faced) tallied to the instance variables above } private boolean isAtEndSpot() { return (this.getAvenue() == 9 && this.getStreet() == 10); } public void NavigateMaze() { while( !this.isAtEndSpot() ) { // All you really need is 14 lines of code to navigate Maze, including squiggles, // making sure only to put down a thing if there is a thing in the backpack, otherwise // just move without putting down a thing! Of course, if you need to use more than // 14 lines of code that’s okay too (for instance, 18 or 20 or 24 lines, but not 200!) } // Print everything here } } // Finally, down in main, change the number of things in backpack to at least 100
45
Assignment 3: The Maze The Basic Move Logic: Turn Left (or Right) While the front is NOT clear Turn Right (or Left) Move
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.