1 / 65

Lecture 3

Lecture 3. Mathematical Expressions, Return Types, and Introduction to Parameters. Reminder: Lecture slides. Lecture slides are posted online and are available before class Use these as a resource during class and outside of class!

Télécharger la présentation

Lecture 3

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. Lecture 3 Mathematical Expressions, Return Types, and Introduction to Parameters

  2. Reminder: Lecture slides Lecture slides are posted online and are available before class Use these as a resource during class and outside of class! If you can, download the lecture before class so you can take notes on the slides.

  3. Some Clarifications… What is this? public class RobotMover { /* additional code elided */ public void moveRobot(Robot samBot) { samBot.moveForward(4); samBot.turnRight(); samBot.moveForward(1); samBot.turnRight(); samBot.moveForward(3); } } This is called a comment Comments are not executed when the program is run They can help you document your code, making it easier for other people (and even you!) to understand what your code is doing when it is read later /* You can make a comment like this */ // Or like this!

  4. Some Clarifications… public class RobotMover { /* additional code elided */ public void moveRobot(Robot samBot) { samBot.moveForward(4); samBot.turnRight(); samBot.moveForward(1); samBot.turnRight(); samBot.moveForward(3); } } • How does samBotknow how to moveForwardand turnRight? The “magic” of CS15: Support Code The support code tells samBot how to moveForwardand turnRight, but it is up to you to tell samBotto do these things!

  5. This Lecture: Mathematical functions in Java More complicated methods with inputs and outputs The constructor Creating instances of a class

  6. Defining Methods • We know how to define simple methods • Today, we’ll define more complicated methods, methods with inputs and outputs • Along the way, learn the basics of manipulating numbers in Java

  7. Calculator • We’ll define a class that models a basic Calculator • Each of the Calculator’s methods will have input (numbers) and output (numeric answer)

  8. Basic math in Java • First, we’ll talk about numbers and mathematical expressions in Java

  9. Integers • An integer is a whole number, positive or negative, including 0 • Depending on size of the integer, we can use one of four numerical base types (primitive Java data types): byte, short, int, and long, in order of number of bits of precision • Bit: binary digit, 0 or 1

  10. Integers In CS15, you will almost always use int

  11. Floating Point Numbers • Sometimes, need more precision than integers can provide • How to represent pi = 3.14159...? • We use floating point numbers for a more precise representation • called “floating point” because decimal point can “float”-- no fixed number of digits before and after it-- historical nomenclature • used for representing numbers in “scientific notation”, with decimal point and exponent, e.g., 4.3 x 10-5 • Two numerical base types in Java represent floating point numbers: float and double

  12. Floating Point Numbers Feel free to use both in CS15. Usually, though, you won’t need the level of precision that doubleprovides

  13. Operators and Math Expressions • Example expressions: 4 + 5 3.33 * 3 10 % 4 3 / 2 3.0 / 2.0

  14. Operators and Math Expressions • Example expressions: 4 + 5→ 9 3.33 * 3→ 9.99 10 % 4 → 2 3.0 / 2.0 → 1.50 3 / 2→ 1 • What does each of these expressions evaluate to? why???

  15. Be careful with integer division! 3 / 2→ 1 3.0 / 2→ 1.50 3 / 2.0→ 1.50 3.0 / 2.0→ 1.50 • When dividing two integers, result is truncated to an integer • 3 / 2 evaluates to 1 • If either number involved is floating point, result is also floating point: allows greater precision

  16. Evaluating Math Expressions • Java follows same evaluation rules that you learned in math class years ago • Evaluation takes place left to right, except: • expressions in parentheses evaluated first, starting at the innermost level • operators evaluated in order of precedence/priority (* has priority over +) 2 + 4 * 3 - 7 → 7 (2 + 3) + (11 / 12)→ 5 3 + (2 - (6 / 3))→ 3

  17. Calculator • Now we can start to think about our Calculator class • Calculators should be able to add, subtract, multiply, and divide • When we tell a Calculator to add two numbers, want it to add them and then tell us the answer • To do this, we need to learn how to write a method that returns a number (or another data type)

  18. Return Type • The return type of a method is the kind of data it gives back to whoever called it public class Robot { public void turnRight() { // code that turns robot right } public void moveForward(int numberOfSteps) { // code that moves robot forward } public void turnLeft() { this.turnRight(); this.turnRight(); this.turnRight(); } } So far, we’ve seen return type void A method with a return type of void doesn’t give back anything when it’s done executing void just means “this method doesn’t return anything.”

  19. Return Type A silly example: publicintgiveMeTwo() { return 2; } • If we want a method to return something, we replace void with the type of thing we want to return • If method should return an integer, specify int as the return type • When return type is not void, we’ve promised to end the method with a return statement This is a return statement. Return statements always take the form: return <something of specified return type>;

  20. Calculator public class Calculator { /* Some code elided */ } • Let’s write a method for Calculator that adds two particular numbers and returns the result: addFiveAndSeven • It will return value of expression “5+7” to whoever called it • We’ll generalize it soon...

  21. Calculator public class Calculator { /* Some code elided */ public int addFiveAndSeven() { return 5 + 7; } } • Let’s write a method for Calculator that adds two particular numbers and returns the result: addFiveAndSeven • It will return value of expression “5+7” to whoever called it • We’ll generalize it soon...

  22. Calculator • What does it mean for method to “return a value to whoever calls it”? • Another object can call addFiveAndSeven on a Calculator from somewhere else in our program and use the result • For example, consider a MathStudent class that has a Calculator named myCalculator • We’ll demonstrate how the MathStudent can call the method and use the result

  23. Calculator /* Somewhere in the MathStudent class lives a Calculator named myCalculator. */ myCalculator.addFiveAndSeven(); public class Calculator { /* Some code elided */ public int addFiveAndSeven() { return 5 + 7; } } • We start by just calling the method • This is fine, but we’re not doing anything with the result! • Let’s use the returned value by printing it to the console

  24. Calculator /* Somewhere in the MathStudent class lives a Calculator named myCalculator. */ myCalculator.addFiveAndSeven(); System.out.println(myCalculator.addFiveAndSeven()); public class Calculator { /* Some code elided */ public int addFiveAndSeven() { return 5 + 7; } } • To print to the console, we use System.out.println • Calling method println on System.out, which is the “standard” output stream • println prints out value of the expression you provide within the parentheses

  25. Calculator /* Somewhere in the MathStudent class lives a Calculator named myCalculator. */ myCalculator.addFiveAndSeven(); System.out.println(myCalculator.addFiveAndSeven()); public class Calculator { /* Some code elided */ public int addFiveAndSeven() { return 5 + 7; } } argument • We’ve provided the expression myCalculator.addFiveAndSeven() to be printed to the console • This information we give to the println method is called an argument: more on this in a few slides • Putting one method call inside another like this is called nesting of method calls

  26. Aside: Nesting • Remember our samBot’s moveForward method? • public void moveForward(int numberOfSteps) { • // code that moves robot forward • } • When we call samBot.moveForward, we need to tell her how many steps to move forward by: • samBot.moveForward(5); • What if we want to calculate a number using our myCalculator, and then tell samBot to move forward by that much?

  27. Aside: Nesting • myCalculator.addFiveAndSeven() returns an int, 12 • samBot.moveForwardtakes in an int • We can nest myCalculator’s method within samBot’s moveForward method: samBot.moveForward(myCalculator.addFiveAndSeven()); returns 12 samBot.moveForward( 12 ); • And samBot will move forward 12 steps!

  28. Calculator /* Somewhere in the MathStudent class lives a Calculator named myCalculator. */ myCalculator.addFiveAndSeven(); System.out.println(myCalculator.addFiveAndSeven()); public class Calculator { /* Some code elided */ public int addFiveAndSeven() { return 5 + 7; } } argument • When this line of code is evaluated: • First, addFiveAndSeven is called on myCalculator, returning the number 12 • Next, println is called on System.out, and 12 is printed to the console

  29. Aside: System.out.println • System.out.println is an awesome tool for testing and debugging your code-- learn to use it! • Lets you see what’s happening in your code by printing out values as it executes • If Calculatorprogram isn’t behaving properly, can test whether method addFiveAndSeven is the problem by printing return value to verify that it’s “12”

  30. Calculator: a generic addmethod • Now Calculators can add two specific numbers-- but that’s not too useful public class Calculator { public intaddFiveAndSeven() { return 5 + 7; } public intaddTwoAndThree() { return 2 + 3; } public intaddSixAndEight() { return 6 + 8; } // ... } For a functional Calculator, we’d have to define new addmethod for every distinct pair of numbers!

  31. Calculator: a generic addmethod • Can do much better-- let’s design a generic method that will add any two numbers we want • Want a method that corresponds to algebraic function: f(x, y) = x + y • public class Calculator { • public intaddFiveAndSeven() { • return 5 + 7; • } }

  32. Calculator: a generic addmethod Mathematical function: f(x, y) = x + y Equivalent Java method: public int add(int x, int y) { return x + y; }

  33. Calculator: a generic addmethod Mathematical function: f(x, y) = x + y Equivalent Java method: public int add(int x, int y) { return x + y; } input name output input name output

  34. Calculator: a generic addmethod • addtakes in two integers from the caller, and gives different answers depending on those integers public class Calculator { /* Some code elided */ public int add(int x, int y) { return x + y; } } Extra pieces of information that a method takes in are called parameters addtakes in two parameters, “x” and “y” -- these, like variable names in an equation, are arbitrary, i.e., your choice parameters

  35. Parameters • General form of a method that takes in parameters: <visibility> <returnType> <methodName>(<type1> <name1>, <type2> <name2>...) { <body of method> } • Parameters are specified as comma-separated list • For each parameter, specify type (for example, int or float), and then name (“x”, “y”, “banana”... whatever you want!) • In algebra, don’t specify type because context makes clear what kind of number we want. In programming use many different types, and must tell Java explicitly what we intend

  36. Parameters • Name of each parameter is almost completely up to you • It’s the name by which you’ll refer to the parameter throughout the method • The following methods are completely equivalent: public int add(int x, int y) { return x + y; } type type name name

  37. Parameters public int add(int a, int b) { return a + b; } • Name of each parameter is almost completely up to you • It’s the name by which you’ll refer to the parameter throughout the method • The following methods are completely equivalent: type type name name

  38. Parameters public int add(int first, int second) { return first + second; } • Name of each parameter is almost completely up to you • It’s the name by which you’ll refer to the parameter throughout the method • The following methods are completely equivalent: type type name name

  39. Parameters public int add(int bert, int ernie) { return bert + ernie; } • Name of each parameter is almost completely up to you • It’s the name by which you’ll refer to the parameter throughout the method • The following methods are completely equivalent: type name type name

  40. Parameters • Remember Robot class from last lecture? • Its moveForward method took in a parameter-- an int named numberOfSteps • Follows same parameter format: type, then name. public void moveForward(int numberOfSteps) { // code that moves the robot // forward goes here! } type name

  41. With great power comes great responsibility... • Try to come up with descriptive names for parameters that make their purpose clear to anyone reading your code • Robot’s moveForward method calls its parameter “numberOfSteps”, not “x” or “thingy” • We use “x” and “y” for simple, generic addmethod-- but for anything more complicated, try to avoid single-letter names

  42. Calculator • Let’s give Calculator class more functionality by defining subtract, multiply, and divide methods! public class Calculator { public int add(int x, int y) { return x + y; } }

  43. Calculator • Try to define three new methods for Calculator: subtract, multiply, and divide • Each method should take in two integers as parameters, and return the result of its respective operation on those two integers public class Calculator { public int add(int x, int y) { return x + y; } // Your code for subtract goes here! // … // … // Your code for multiply goes here! // … // … // Your code for divide goes here! // … // … }

  44. Calculator • Here’s one possible solution • We arbitrarily chose “x” and “y” for names of each method’s parameters public class Calculator { public int add(int x, int y) { return x + y; } public int subtract(int x, int y) { return x - y; } public int multiply(int x, int y) { return x * y; } public int divide(int x, int y) { return x / y; } }

  45. Calling Methods with Parameters • Now that we’ve defined add, subtract, multiply, and divide methods, can call them on any Calculator • Want to call add method and tell it which two numbers to add • How do we call a method that takes in parameters?

  46. Calling Methods with Parameters • You already know how to call a method that takes in one parameter! • Remember moveForward? public void moveForward(int numberOfSteps) { // code that moves the robot // forward goes here! }

  47. Calling Methods with Parameters • When we call a method, we pass it any extra piece of information it needs as an argument within the parentheses. public class RobotMover { /* additional code elided */ public void moveRobot(Robot samBot) { samBot.moveForward(4); samBot.turnRight(); samBot.moveForward(1); samBot.turnRight(); samBot.moveForward(3); } } arguments moveForward takes in one int

  48. Arguments and Parameters parameter // within the Robot class public void moveForward(int numberOfSteps) { // code that moves the robot // forward goes here! } // within the RobotMover class public void moveRobot(Robot samBot) { samBot.moveForward(4); samBot.turnRight(); samBot.moveForward(1); samBot.turnRight(); samBot.moveForward(3); } argument argument • In defining a method, the parameter is the name by which a method refers to a piece of information passed to it-- e.g. “x” and “y” in the function f(x, y) = x + y - it is a “dummy name” determined by the definer • In calling a method, an argument is the actual value passed -- e.g. 2 and 3 in f(2, 3) argument

  49. Calling Methods That Have Parameters • When moveForward executes, its parameter is assigned the value of the argument that was passed in • That means moveForward here executes with numberOfSteps = 3 // in some other class... samBot.moveForward(3); ____________________________________________ // in the Robot class... public void moveForward(int numberOfSteps) { // code that moves the robot // forward goes here! } When we call samBot.moveForward(3), we’re passing the number 3 as an argument

  50. Calling Methods That Have Parameters • When calling a method that takes in parameters, must provide a valid argument for each parameter • This means that the number and type of arguments must match the number and type of parameters: 1-to-1 correspondence • Order matters! The first argument you provide will correspond to the first parameter, the second to the second, etc.

More Related