Algorithms and Patents Aaron Bloomfield CS 4102 Spring 2011 1.
1 Methods Chapter 5 Spring 2007 CS 101 Aaron Bloomfield.
-
Upload
georgina-harris -
Category
Documents
-
view
213 -
download
1
Transcript of 1 Methods Chapter 5 Spring 2007 CS 101 Aaron Bloomfield.
1
Methods
Chapter 5Spring 2007CS 101Aaron Bloomfield
2
Preparation Scene so far has been background material and experience
Computing systems and problem solving Variables Types Input and output Expressions Assignments Using objects Standard classes and methods Decisions (if, switch) Loops (while, for, do-while)
Next: Experience what Java is really about Design and implement objects representing information
and physical world objects
3
Object-oriented programming Basis
Create and manipulate objects with attributes and behaviors that the programmer can specify
Mechanism Classes
Benefits An information type is design and implemented once
Reused as needed No need reanalysis and re-justification of the
representation
4
Known Classes Classes we’ve seen
BigInteger String Rectangle Vector Scanner System
Classes we’ll be seeing soon BigDecimal
But the first step is on creating methods…
55
MethodsMethods
6
Methods we’ve seen We’ve seen methods (functions) before
angleSin = Math.sin (90 * PI/180.0); System.out.println (“Hello world”); value = card.getBlackjackValue();
We are going to start defining them
Note that many of these “return” a value Math.sin() and card.getBlackjack()
The way to name methods is the same as variables allTheWordsTogether With the first letter of each word capitalized Except the very first letter is lower case
7
Our first class with methodspublic class Methods1 {
public static void main (String args[]) {Scanner stdin = new Scanner (System.in);System.out.println ("Enter a valid int value");int value = stdin.nextInt();if ( value == 1 ) validValue();else if ( value == 2 ) validValue();else if ( value == 3 ) invalidValue();else if ( value == 4 ) invalidValue();else validValue();
}
}
8
Our first class with methods, continued
public static void invalidValue() { System.out.println ("You have entered an invalid value."); System.out.println ("The program will now exit."); System.exit (0);
}
public static void validValue() { System.out.println ("You have entered an valid value."); System.out.println ("Congratulations!"); System.out.println ("The program will now exit."); System.exit (0);
}
99
Program DemoProgram Demo
Methods1.javaMethods1.java
10
public static void validValue() { System.out.println ("You have entered an valid value."); System.out.println ("Congratulations!"); System.out.println ("The program will now exit."); System.exit (0);
}
public static void main (String args[]) { Scanner stdin = new Scanner (System.in); System.out.println ("Enter a valid int value"); int value = stdin.nextInt(); if ( value == 1 ) validValue();
// ... }
What’s happening there
Scanner
stdin
value 1
11
Notes on these methods At this point, all methods in the class are static
We will be discussing what static means later in this slide set
Until then, I’ll be ignoring it, and just telling you when things should and should not be static Sorry!
None of those two methods return a value Notice the “void” before the method name
And none take in any parameters Notice the empty parameters after the method name
1313
1414
A previous HW J3A previous HW J3
15
16
Revamping last semester’s HW J3
Start over
Publicdanger
Defensecontractor
Promoted
Cynicalguru
Becomea coder
Done tech support?
Been asysadmin?
Workedwith NT?
Want toplay
w/nukes?
Hatepeople?
Bitteryet?
Successfulmanaging?
Starthere
Start over
A revised HW 3 flowchart
Green paths are “yes” paths, red are “no” paths
We’ll make a slight modification to the diagram:
Note that this part is repeated twice!
17
HW J3 Code The yellow
boxed part is what was repeated from the previous slide
if ( extractor.askUser(Q_TECH_SUPPORT) ){ if ( extractor.askUser(Q_BITTER_YET) )
if ( extractor.askUser(Q_MANAGEMENT) ) System.out.println (A_CYNICAL);else System.out.println (A_PROMOTED);
elseSystem.out.println (A_START_OVER);
} else if ( extractor.askUser(Q_BEEN_SYSADMIN) ){ if ( extractor.askUser(Q_HATE_PEOPLE) ) {
System.out.println (A_CODER); } else if ( extractor.askUser(Q_WINNT) ){
if ( extractor.askUser(Q_NUCLEAR_WEAPONS) ) System.out.println (A_DEFENSE_CONTRACTOR);else System.out.println (A_PUBLIC_DANGER);
} elseSystem.out.println (A_START_OVER);
} else if ( extractor.askUser(Q_WINNT) ){ if ( extractor.askUser(Q_NUCLEAR_WEAPONS) )
System.out.println (A_DEFENSE_CONTRACTOR); else
System.out.println (A_PUBLIC_DANGER);} else System.out.println (A_START_OVER);
18
HW J3 Code with methods The yellow
boxed part is what was repeated from the previous slide
if ( extractor.askUser(Q_TECH_SUPPORT) ){ if ( extractor.askUser(Q_BITTER_YET) )
if ( extractor.askUser(Q_MANAGEMENT) ) System.out.println (A_CYNICAL);else System.out.println (A_PROMOTED);
elseSystem.out.println (A_START_OVER);
} else if ( extractor.askUser(Q_BEEN_SYSADMIN) ){ if ( extractor.askUser(Q_HATE_PEOPLE) ) {
System.out.println (A_CODER); } else
doBottomPartOfFlowchart();} else doBottomPartOfFlowchart();
19
HW J3 Code with methods The doBottomPartOfFlowchart method:
public static void doBottomPartOfFlowchart() { if ( extractor.askUser(Q_WINNT) ){
if ( extractor.askUser(Q_NUCLEAR_WEAPONS) ) System.out.println (A_DEFENSE_CONTRACTOR);else System.out.println (A_PUBLIC_DANGER);
} elseSystem.out.println (A_START_OVER);
}
20
What happened here We took a common set of code
Wrote it once But used it multiple times (twice in this case)
Granted, the code was a small segment (7 lines) But, in other programs, could be very large
This is called Refactoring It is an essential principle of software engineering Has other names: factoring (notice there is no ‘re’ at the
beginning), extracting a method, etc.
21
Pros of Refactoring Benefits of Refactoring
Reduce length of code As you don’t have to repeat that section of code
multiple times Make code easier to read
The main if-else-if statement is shorter, thus easier to understand what’s going on
Changes are easier to make If we want to modify that part of the flowchart, we only
have to do it once Rather than searching for each of the repeated code
segments in a program
22
Cons of Refactoring Drawbacks of Refactoring
Because you are calling another method, it will be slightly slower On the order of a few nanoseconds Modern compilers can sometimes eliminate this
penalty
The general consensus is that the benefits of Refactoring far outweigh the drawback(s)
2323
2424
Return ValuesReturn Values
25
The return keyword The return keyword immediately stops execution of a method
And jumps back to whatever called that method And possibly returns a value (we’ll see this next)
Consider the following method
public static void foo (int x) { if ( x == 1 ) return; System.out.println (“x is not 1”);}
This method will only print the String if x is not 1
26
Return values At some point in those methods, Java must be told to take a value
and “pass” it back
Consider angleSin = Math.sin (90 * PI/180.0); At some point in the Math.sin() method, the sin has been
computed And that value must be “passed back” to be stored in angle
Consider value = card.getBlackjackValue(); At some point in the card.getBlackjackValue() method, the value
has been computed And that value must be “passed back” to be stored in value
This is called “returning” a value from a method
Note that some methods don’t return a value System.out.println(), for example
27
Return values (aka return types)public class Methods2 {
public static int returnsAValue () { return 1;
}
public static double alsoReturnsAValue() { return 1.0;
}
public static void main (String args[]) { int value1 = returnsAValue(); System.out.println (value1);
double value2 = alsoReturnsAValue(); System.out.println (value2);
// The following line requires a cast int value3 = (int) alsoReturnsAValue(); System.out.println (value3);
}
}
2828
Program DemoProgram Demo
Methods2.javaMethods2.java
29
Return types All a return statement does is take the value
Which could be a number Or a value in a variable Or an expression (such as x+1)
And “pass” it back to whatever called the method
30
How well do you feel you How well do you feel you understand return values?understand return values?
a)a) Very well! This stuff is so easy.Very well! This stuff is so easy.
b)b) With a little review, I’ll be good.With a little review, I’ll be good.
c)c) Not very well at all.Not very well at all.
d)d) I’m so lost. What’s a return type I’m so lost. What’s a return type again?again?
e)e) I’d rather not answer this question, I’d rather not answer this question, thanks.thanks.
31
Parameters Sometimes you need to pass in parameters to tell a method
how to perform Consider Math.sin() – it needs to know the angle
The parameters are listed between the parenthesis after the method name
public static void main (String args[])
The methods we will study next compute (and return) x2, x3, and x4
32
The methods
public static int square (int x) {int theSquare = x * x;return theSquare;
}
public static int cube (int x) {return x * x * x;
}
public static int fourthPower (int x) {return square(x) * square(x);
}
33
A method with multiple parameters
public static int squareOrCube (int which, int value) {if ( which == 1 ) return value * value;else if ( which == 2 ) { int cube = value * value * value; return cube;} else return 0;
}
34
The main() methodimport java.util.*;
public class Methods3 {
// the previous methods go here
public static void main (String args[]) { Scanner stdin = new Scanner (System.in); System.out.println ("Enter an int value"); int value = stdin.nextInt(); int theSquare = square(value); System.out.println ("Square is " + theSquare); System.out.println ("Cube is " + cube (value)); System.out.println ("Square is " + squareOrCube (1, value)); System.out.println ("Cube is " + squareOrCube (2,value)); System.out.println ("Fourth power is " + fourthPower (value));
}
}
3535
Program DemoProgram Demo
Methods3.javaMethods3.java
3636
37
Returning objects We can also return objects from methods
What gets returned is the reference to the object
public class Methods4 {
public static String getCourse () {String name = "CS 101";return name;
}
public static void main (String args[]) {String courseName = getCourse();System.out.println (courseName);
}
}
String
“CS 101”
courseName
name
3939
Program DemoProgram Demo
Methods4.javaMethods4.java
40
Modifying parameters Consider the following code
public class Methods5 {
public static void changeValue (int x) { x = 7;
}
public static void main (String args[]) { int y = 5; changeValue(y); System.out.println (y);
}
}
What gets printed?
4141
Program DemoProgram Demo
Methods5.javaMethods5.java
42
Pass by value Java is a pass-by-value language
This means that a COPY of the parameter’s value is passed into the method If a method changes that value, only the COPY is changed Once the method returns, the copy is forgotten And thus the change is not visible outside the method
There are other manners of returning values that are used in other languages Pass by reference Pass by name (nobody uses this anymore)
We will see about trying to change object parameters later in this slide set
43
How well do you feel you How well do you feel you understand parameters?understand parameters?
20% 20% 20%20%20%1.1. Very well! This Very well! This stuff is easy!stuff is easy!
2.2. Fairly well – with Fairly well – with a little review, I’ll a little review, I’ll be goodbe good
3.3. Okay. It’s not Okay. It’s not great, but it’s not great, but it’s not horrible, eitherhorrible, either
4.4. Not well. I’m Not well. I’m kinda confusedkinda confused
5.5. Not at all. I’m Not at all. I’m soooooo lostsoooooo lost
44
Variable scoping A variable is visible within the block it is declared
Called the “scope” of the variable
public class Scoping {static int z
public static void foo (int x) {// ...
}
public static void bar () {// ...
}
public static void main (String[] args) {int y;// ...
}}
This local variable is visible until the end of the main() method
This variable is visible anywhere in the Scoping class
This parameter is visible only in the foo() method
45
How well do you feel you How well do you feel you understand variable understand variable
scoping?scoping?20% 20% 20%20%20%1.1. Very well! This Very well! This
stuff is easy!stuff is easy!2.2. Fairly well – with Fairly well – with
a little review, I’ll a little review, I’ll be goodbe good
3.3. Okay. It’s not Okay. It’s not great, but it’s not great, but it’s not horrible, eitherhorrible, either
4.4. Not well. I’m Not well. I’m kinda confusedkinda confused
5.5. Not at all. I’m Not at all. I’m soooooo lostsoooooo lost
46
Method notes summary You can put the methods in a class in any order
Java doesn’t care which one is listed first Thus, you can call a method listed later in the method
This is different than C/C++
All methods must specify a return type If it’s void, then no value is returned
Parameters can’t be changed within a method Although the objects that the parameters point to can be
4747
Agricultural Agricultural historyhistory
PhysicsPhysics MedicineMedicine LiteratureLiterature PeacePeace EconomicsEconomics
ChemistryChemistry BiologyBiology NutritionNutrition
Fluid dynamicsFluid dynamics
The 2005 Ig Nobel PrizesThe 2005 Ig Nobel Prizes““The Significance of Mr. Richard Buckley’s Exploding The Significance of Mr. Richard Buckley’s Exploding
Trousers”Trousers”
The pitch drop experiment, started in 1927The pitch drop experiment, started in 1927
Neuticles – artificial replacement testicles for dogsNeuticles – artificial replacement testicles for dogs
The 409 scams of Nigeria for a “cast of rich characters”The 409 scams of Nigeria for a “cast of rich characters”
Locust brain scans while they were watching Star WarsLocust brain scans while they were watching Star Wars
For an alarm clock that runs away, thus making people For an alarm clock that runs away, thus making people more productivemore productive
““Will Humans Swim Faster or Slower in Syrup?”Will Humans Swim Faster or Slower in Syrup?”
For cataloging the odors of 131 different stressed frogsFor cataloging the odors of 131 different stressed frogs
To Dr. Yoshiro Nakamats who catalogued and analyzed To Dr. Yoshiro Nakamats who catalogued and analyzed every meal he ate for the last 34 years (and every meal he ate for the last 34 years (and counting)counting)
““Pressures Produced When Penguins Pooh – Pressures Produced When Penguins Pooh – Calculations on Avian Defaecation”Calculations on Avian Defaecation”
4848
More on parameter passingMore on parameter passing
49
Modifying parameters Consider the following code
public class Methods5 {
public static void changeValue (int x) { x = 7;
}
public static void main (String args[]) { int y = 5; changeValue(y); System.out.println (y);
}
}
What gets printed? 5 is printed
5y
5x 7x
5050
Program DemoProgram Demo
Methods5.javaMethods5.java
51
Pass by value Java is a pass-by-value language
This means that a COPY of the parameter’s value is passed into the method If a method changes that value, only the COPY is changed Once the method returns, the copy is forgotten And thus the change is not visible outside the method
There are other manners of returning values that are used in other languages Pass by reference Pass by name (nobody uses this anymore)
We will see about trying to change object parameters later in this slide set
52
Modifying parameters Consider the following code
import java.awt.*;
public class Methods6 {
public static void changeValue (Rectangle r) {
r.setSize (10,20); }
public static void main (String args[]) {Rectangle rect = new Rectangle(1, 2);changeValue(rect);System.out.println (rect.getWidth());
}
}
What gets printed? 10 is printed
+ Rectangle ()+ Rectangle (int width, int height)+ setSize (int width, int height)+ getWidth ()
Rectangle
- width = 1 - height = 2
rect
+ Rectangle ()+ Rectangle (int width, int height)+ setSize (int width, int height)+ getWidth ()
Rectangle
- width = 10 - height = 20r
5353
Program DemoProgram Demo
Methods6.javaMethods6.java
5454
Fan-supplied demotivators!Fan-supplied demotivators!
55
Pass by value Java is still a pass-by-value language
This means that a COPY of the parameter’s value is passed into the method But the parameter is a REFERENCE to an object The object itself is not passed So any changes to the reference are forgotten about But you can modify the object it refers to
56
Modifying parameters Consider the following code
import java.awt.*;
public class Methods7 {
public static void changeValue (Rectangle r) {
r = new Rectangle (10,20); }
public static void main (String args[]) {Rectangle rect = new Rectangle(1, 2);changeValue(rect);System.out.println (rect.getWidth());
}
}
What gets printed? 1 is printed
+ Rectangle ()+ Rectangle (int width, int height)+ setSize (int width, int height)+ getWidth()
Rectangle
- width = 1 - height = 2
rect
+ Rectangle ()+ Rectangle (int width, int height)+ setSize (int width, int height)+ getWidth()
Rectangle
- width = 10 - height = 20
r
The only change!
5757
Program DemoProgram Demo
Methods7.javaMethods7.java
58
Pass by value Java is still a pass-by-value language
This means that a COPY of the parameter’s value is passed into the method But the parameter is a REFERENCE to an object The object itself is not passed So any changes to the reference are forgotten about But you can modify the object it refers to
59
How well do you feel you How well do you feel you understand parameter understand parameter
passing?passing?20% 20% 20%20%20%1.1. Very well! This Very well! This
stuff is easy!stuff is easy!2.2. Fairly well – with Fairly well – with
a little review, I’ll a little review, I’ll be goodbe good
3.3. Okay. It’s not Okay. It’s not great, but it’s not great, but it’s not horrible, eitherhorrible, either
4.4. Not well. I’m Not well. I’m kinda confusedkinda confused
5.5. Not at all. I’m Not at all. I’m soooooo lostsoooooo lost
60
A frisbee demo of parameter passing…
61
How well do you feel you How well do you feel you understand parameter understand parameter
passing?passing?20% 20% 20%20%20%1.1. Very well! This Very well! This
stuff is easy!stuff is easy!2.2. Fairly well – with Fairly well – with
a little review, I’ll a little review, I’ll be goodbe good
3.3. Okay. It’s not Okay. It’s not great, but it’s not great, but it’s not horrible, eitherhorrible, either
4.4. Not well. I’m Not well. I’m kinda confusedkinda confused
5.5. Not at all. I’m Not at all. I’m soooooo lostsoooooo lost
6262
Today’s demotivatorsToday’s demotivators