Instructor: Craig Duckett cduckett@cascadia.edu Another Look at Extending a Class Can do • A move(); • B turnleft(); • C pickThing(); Robot extends MrRoboto Can do … • A • B • C BIT 115: Introduction To Programming … and new methods • X turnAround(); • Y move3(); • Z turnRight(); 2 Another Look at Extending a Class Can do • A • B • C Robot extends MrRoboto Can do … • A • B • C … and new methods • X • Y • Z So, if you want a robot that can only do A, B, and C, then instantiate: Robot lisa = new Robot(bothell, 3, 2, Direction.SOUTH); But, if you want a robot that can do A, B, and C and X, Y, and Z, then instantiate: MrRoboto lisa = new MrRoboto(bothell, 3, 2, Direction.SOUTH); BIT 115: Introduction To Programming 3 Another Look at Extending a Class BIT 115: Introduction To Programming 4 Some More Methods (Robot Class) 5 Some More Methods (Robot Class) Up until now we’ve been making use of just a few Robot class methods, like move(), turnLeft(), putThing(), and pickThing(), as well as some new methods we might have created like turnaround(), move3(), or turnRight(). Here are some additional Robot class methods that we are going to start introducing into our programs: • • • • • • frontIsClear() – Checks to see if the front is clear countThingsInBackpack() – Checks number of things in backpack canPickThing() – Checks to see if a thing is on intersection getDirection() – Checks the direction the robot is facing getStreet() – Checks the street number robot is on getAvenue() – Checks the avenue number robot is one How these can be used in a program will make more sense after I’ve finished discussing the if and while statements in the next portion of the lecture Go to Becker Library: http://www.learningwithrobots.com/doc/ Select becker.robots from top left column, then Robot from bottom left column, then scroll over to the Method Summary section in the center right window 6 Basic Decision-Making BIT 115: Introduction To Programming 7 Chapter 4.1: Two Kinds of Decisions If and While Statements • • • • Use an if statement to perform an action once or not at all. Use a while statement to perform an action zero or more times. Use an if-else statement to perform either one action or another action. Use a while statement to perform an action a specified number of times. Up to now, a robot’s exact initial situation was known at the start of a task. When we wrote our programs, this information allowed robots to find things and avoid running into walls. However, these programs worked only in their specific initial situations. If a robot tried to execute one of these programs in a slightly different initial situation, the robot would almost certainly fail to perform the task. To address this situation, a robot must make decisions about what to do next. Should it move or should it pick something up? In this chapter we will learn about programming language statements that test the program’s current state and choose the next statement to execute based on what they find. One form of this capability is the if statement: If something is true, then execute a group of statements. If it is not true, then skip the group of statements. Another form of this capability is the while statement: while something is true, execute a group of statements. BIT 115: Introduction To Programming 8 Two Kinds of Decisions So far, our programs have been composed of a sequence of statements executed in order. The if and while statements are different. As the program is running, they can ask a question. Based on the answer, they choose the next statement or group of statements to execute. In a robot program, the question asked might be, “Is the robot’s front blocked by a wall?” or “Is there something on this intersection the robot can pick up?” All of these questions have “yes” or “no” answers. In fact, if and while statements can only ask yes and no questions. Java uses the keyword true for “yes” and false for “no.” These keywords represent Boolean values, just like the numbers 0 and 23 represent integer values. George Boole (2 November 1815 – 8 December 1864) was an English-born mathematician, philosopher and logician. His work was in the fields of differential equations and algebraic logic, and he is now best known as the author of The Laws of Thought. As the inventor of the prototype of what is now called Boolean logic, which became the basis of the modern digital computer, Boole is regarded in hindsight as a founder of the field of computer science. 9 If and While When the simplest form of an if statement asks a question and the answer is true, it executes a group of statements once and then continues with the rest of the program. If the answer to the question is false, that group of statements is not executed. When a while statement asks a question and the answer is true, it executes a group of statements (just like the if statement). However, instead of continuing down to the rest of the program, the while statement asks the question again. If the answer is still true, that same group of statements is executed again. This continues until the answer to the question is false. The if statement’s question is “Should I execute these statements at least once?” if (test statement) { // list of statements } The while statement’s question is “Should I execute these statements again?” while (test statement) { // list of statements } 10 If: “Once or not at all” Example: If Statement ASKS THE QUESTION: Should this statement or group of statements be executed once or not at all? Once Not At All MsRobotoIf.java 11 While: “Loop as long as true” Example: While Statement ASKS THE QUESTION: Should this statement or group of statements be executed again? Yes No MsRobotWhile.java 12 BIT 115: Introduction To Programming 13 Built-In Queries, Predicates The Robot class has several built-in queries that answer questions like • • • • • • Can I pick a Thing up from this Intersection? boolean canPickThing() How many Things are in my backpack? int countThingsInBackpack() What am I called (what string of characters is labeling me)? String getLabel() What Avenue am I on? int getAvenue() What is my speed? int getSpeed() What Street am I on? int getStreet() Questions with Boolean True or False answers, like canPickThing, are called predicates. Negating a predicate gives it the opposite meaning. BIT 115: Introduction To Programming 14 Logical Negation Operator The Robot class does not provide a predicate for testing if the Robot cannot pick up a Thing. Fortunately, any Boolean expression may be negated, or given the opposite value, by using the logical negation operator “ ! ”. In English, this is usually written and pronounced as “not”. ! means “not” Logical Negation Operator BIT 115: Introduction To Programming 15 Testing Integer Queries The if and while statements always ask True or False questions. “Should I execute the code, true or false?” This approach works well for queries that return a boolean value, but how can we use queries that return integers? We do it with comparison operators BIT 115: Introduction To Programming 16 Using Comparison Operators: A Few Snippets of Code while(bob.countThingsInBackpack() > 0) // What does this do? { bob.puThing(); bob.move(); } if(bob.getDirection() == Direction.WEST) // What does this do? { bob.turnLeft(); bob.turnLeft(); } while(bob.getDirection() != Direction.NORTH) // What does this do? { bob.turnLeft(); } 17 Two-Sided Queries The examples in the comparison operator table show an integer on only one side, but Java is more flexible than this: it can have a query on both sides of the operator, as in the following statements -- This test determines whether karel is on the diagonal line of intersections (0,0), (1,1), (2,2), and so on. It also includes intersections with negative numbers such as (-3, -3). The following code tests whether the robot’s Avenue is five more than the Street. Locations where this tests true include (0,5) and (1,6). BIT 115: Introduction To Programming 18 The If-Else Statement The if statement performs an action once or not at all. Another version of the if statement, the if-else statement, choose between two groups of actions. It performs one or it performs the other based on a test. Unlike the if statement, the if-else statement always performs an action. The question is, which action? The general form of the if-else is as follows: MsRobotoIfElse.java · MsRobotoWhileIfElse.java · MsRobotoWhileifNot.java 19 A Brief Introduction: Variables and Parameters 20 Brief Intro: Variables & Parameters PLEASE NOTE: We will be going over Variables & Parameters again in more detail in several upcoming Lectures. This is just a teaser or "taste" of things to come A variable is a piece of data like a number that can be changed programmatically (it doesn't have to be the same number over and over again, it isn't constant or set in stone). In other words, a variable can start out one number, like a 0, and be changed by the program into another number, like a 1 or a 2 or a 3, etcetera. 21 Brief Intro: Variables & Parameters PLEASE NOTE: We will be going over Variables & Parameters again in more detail in several upcoming Lectures. This is just a teaser or "taste" of things to come When we set up a variable it is called “declaring the variable.” This “declaration” consists of three parts: • • • The type of data the variable will hold The name of the variable The initial value the variable starts with In programming, the type of data is called data type and can be a whole number (integer or int for short), a number that can contain a decimal point (float), a true or false value (boolean), or even a single character (char). The name of the variable can be anything you want, but by convention it must start with an alphabetical character (never a number) although could also start with an underscore _ or a dollar sign $. It can contain numbers, but again, never at the beginning. In programming, when you give a variable a starting value or initial value this is called initialization. Before you can use a variable, it must first be “initialized”. 22 Brief Intro: Variables & Parameters PLEASE NOTE: We will be going over Parameters & Variables again in more detail in several upcoming Lectures. This is just a teaser or "taste" of things to come A parameter is a variable that you pass into a method (function) when “calling” it in main. Jo.moveExactly(12); If you think back to math class, you spend a lot of time talking about f(x). In that case, 'f' is the function, 'x' is the variable, and the passing of 'x' inside the function's parentheses is the parameter. In other words, something passed to 'x' is going to change what the output of 'f' gives you. Being a variable, 'x' is a placeholder for any number that might be passed to the parameter. 23 Brief Intro: Variables & Parameters Here is an abstract representation of what is going on. 'x' is a variable because it is a placeholder for any number Inside the function f's parentheses, 'x' represents a parameter, because the value of 'x' is going to be passed into the function, and then something is going to be done with it in some way. If 'x' is a 2, then the output of 'f' is 14 If 'x' is a 3, then the output of 'f' is 19 If 'x' is a 4, then the output of 'f' is 26 If 'x' is a 5, then the output of 'f' is 35 If 'x' is a 6, then the output of 'f' is 46 24 Brief Intro: Variables & Parameters Passing a value from the method “call” in main to the method itself. public void dropThingAndMove(int num) { while(this.getAvenue() < num) { this.putThing(); this.move(); } } Jo.dropThingAndMove(10); But, how does this work with Java? Let's take a look at some example code! moveTest.java – moveTest2.java - NumTest.java 25 import becker.robots.*; import java.awt.Color; // Import this Java Library item to change robot color class RobotThatMoves extends Robot { public RobotThatMoves(City c, int st, int ave, Direction dir, int num) { super(c, st, ave, dir, num); } public void moveExactly(int num) { while(this.getAvenue() < num) // getAvenue() checks avenue robot is on { this.move(); } } int num } public class NumTest extends Object { public static void main(String[] args) { City toronto = new City(10,20); RobotThatMoves Jo = new RobotThatMoves(toronto, 4, 0, Direction.EAST, 0); RobotThatMoves Mo = new RobotThatMoves(toronto, 5, 0, Direction.EAST, 0); Jo.setLabel("Jo"); // setLabel() method can be used to ‘name’ robot Jo.setColor(Color.ORANGE); // setColor() method can change robot’s color Mo.setLabel("Mo"); Mo.setColor(Color.PINK); int steps = 7; Jo.moveExactly(steps); // You can pass a ‘named’ variable like ‘steps’… Mo.moveExactly(12); // …or pass the value directly } } int steps FYI: Giving Your Robot a “Label” or a “Color” If you want to give the Robot a label when the program runs, then you will have to do something like this: mary.setLabel("Mary"); If you want to change the Robot's color, then you must include this at the top of your file along with the import becker.robots.*; import java.awt.Color; // This adds the Abstract Windows Toolkit library And then do something like this: mary.setColor(Color.ORANGE); In jGRASP, you will have to use one of the above named 13 standard colors to change a robot’s color. Please note that the color has to be in all caps, like BLUE or GREEN. 27 ICE 3B APPROXIMATE TIME: 1:45-2:30pm You will complete the While/If Worksheet first, then you will work on the Java program BIT 115: Introduction To Programming 28