Building Java Programs Chapter 3 Introduction to Parameters
Building Java Programs Chapter 3: Introduction to Parameters and Objects 1
• parameters Chapter outline – passing parameters to static methods – writing methods that accept parameters • methods that return values – calling methods that return values (e. g. the Math class) – writing methods that return values • using objects – String objects – Point objects – console input with Scanner objects 2
Section 3. 1 Parameters • Consider the task of drawing the following figures: ********************* ***** * * ***** – The lines and figures are similar, but not exactly the same. 3
public class Stars 1 { public static void main(String[]args) { draw. Line. Of 13 Stars(); draw. Line. Of 7 Stars(); draw. Line. Of 35 Stars(); draw 10 x 3 Box(); draw 5 x 4 Box(); } The methods at left are redundant. Would constants help us solve this public static void draw. Line. Of 13 Stars() { problem? - No for (int i = 1; i <= 13; i++) { System. out. print("*"); What would be a better solution? } System. out. println(); } public static void draw. Line. Of 7 Stars() { for (int i = 1; i <= 7; i++) { System. out. print("*"); } System. out. println(); } public static void draw. Line. Of 35 Stars() { for (int i = 1; i <= 35; i++) { System. out. print("*"); } System. out. println(); }. . . draw. Line - A method to draw a line of any number of stars. draw. Box - A method to draw a box of any size. 4
• parameterized method: One that is given extra information (e. g. number of stars to draw) when it is called. • parameter: A value passed to a method by its caller. • Writing parameterized methods requires 2 steps: – write the method to accept the parameter – call the method and pass the parameter value(s) desired main 7 13 draw. Line ************* 5
• Parameterized method declaration syntax: public static void <name> (<type> <name>){ <statement(s)> ; } Example: public static void print. Spaces(int count) { for (int i = 1; i <= count; i++) { System. out. print(" "); } } • Whenever print. Spaces is called, the caller must specify how many spaces to print. Example: print. Spaces(13); 6
public static void main(String[] args) { for (int row = 1; row <= 6; row++) { print. Stars(row); System. out. println(); } } // print num stars public static void print. Stars(int num) { for (int i = 1; i <= num; i++) { System. out. print("*"); } } Actual Parameter or Argument Formal Parameter 7
When passing parameters to a method, the value of the actual parameter is copied into the formal parameter. public static void main(String[] args) { for (int row = 1; row <= 6; row++) { print. Stars(row); System. out. println(); } } // print num stars public static void print. Stars(int num) { for (int i = 1; i <= num; i++) { System. out. print("*"); } } memory 1 row 1 num 8
• When the parameterized method call executes: – the value is copied into the parameter variable – the method's code executes using that value public static void main(String[] args){ print. Spaces(7); print. Spaces(13); count 7 } public static void print. Spaces(int count) { for (int i = 1; i <= count; i++) { System. out. print(" "); } } 9
• Call by value semantics: When primitive variables (int, double) are passed as parameters, their values are copied. – Modifying the parameter inside the method will not affect the variable passed in. public static void main(String[] args) { int x = 23; strange(x); System. out. println("2. x = " + x); . . . } // unchanged Output: public static void strange(int x) { x = x + 1; 1. x = 24 System. out. println("1. x = " + x); 2. x = 23 } Why? Modularization. I can give any name to a variable inside a method and it is unknown outside that method. This includes the names of parameters. The parameter x in strange is declared within strange. 10
Common errors • If a method accepts a parameter, it is illegal to call it without passing any value for that parameter. strange(); // ERROR: parameter value required • The value passed to a method must be of the correct type, matching the type of its parameter variable. strange(3. 7); // ERROR: must be of type int • You will do this in Lab 3. 11
// Prints several lines of stars. // Uses a parameterized method to remove redundancy. public class Stars 2 { public static void main(String[] args) { draw. Line(13); draw. Line(7); draw. Line(35); } // Prints the given number of stars plus a line break. public static void draw. Line(int count) { for (int i = 1; i <= count; i++) { System. out. print("*"); } System. out. println(); } } Output: ******************** 12
• Methods can accept multiple parameters. – The parameters are separated by commas. – When the method is called, it must be passed values for each of its parameters. • Multiple parameters declaration syntax: public static void <name> ( <type> <name> , . . . , <type> <name> ) { <statement(s)> ; } • Multiple parameters call syntax: <name> ( <expression>, . . . , <expression> ); 13
Often have multiple parameters // print the specified character num times public static void print. Chars(int num, char c) { for (int i = 1; i <= num; i++) { System. out. print(c); } } Examples: print. Chars(4, '$'); $$$$ print. Chars(6, '>'); >>>>>> print. Chars(12, '@'); @@@@@@ 14
public static void main(String[] args) { print. Number(4, 9); print. Number(17, 6); print. Number(8, 0); print. Number(0, 8); } public static void print. Number(int number, int count) { for (int i = 1; i <= count; i++) { System. out. print(number); } System. out. println(); } Output: 44444 171717 0000 // Why the blank line? A: count is 0. 15
Stars solution // Prints several lines and boxes made of stars. // Uses multiple parameterized methods. public class Stars 3 { public static void main(String[] args) { draw. Line(13); draw. Line(7); draw. Line(35); System. out. println(); draw. Box(10, 3); draw. Box(5, 4); draw. Box(20, 7); } // Prints the given number of stars plus a line break. public static void draw. Line(int count) { for (int i = 1; i <= count; i++) { System. out. print("*"); } System. out. println(); }. . . 16
. . . Stars solution, cont'd. // Prints a box of stars of the given size. public static void draw. Box(int width, int height) { draw. Line(width); for (int i = 1; i <= height - 2; i++) { System. out. print("*"); print. Spaces(width - 2); System. out. println("*"); } } } draw. Line(width); // Prints the given number of spaces. public static void print. Spaces(int count) { for (int i = 1; i <= count; i++) { System. out. print(" "); } } 17
public class Print. Chars. Example { public static void main(String[] args) { print. Chars(20, '='); // top row System. out. println(); for(int i = 1; i <= 10; i++) { // 1 row per loop print. Chars(i, '>'); print. Chars(20 - 2 * i, ' '); print. Chars(i, '<'); System. out. println(); } } } print. Chars(20, '='); System. out. println(); // bottom row public static void print. Chars(int num, char c) { for (int i = 1; i <= num; i++) { ========== > < System. out. print(c); >> << } >>> <<< } >>>> <<<< >>>>> <<<<< >>>>>> <<<<<< >>>>>>> <<<<<<< >>>>> <<<<< >>>>><<<<< ========== 18
19
20
21
Section 3. 2 Methods that return values Method name Description abs(value) absolute value Java's Math class ceil(value) Constant Description E 2. 7182818. . . PI 3. 1415926. . . rounds up cos(value) cosine, in radians floor(value) rounds down log(value) logarithm, base e log 10(value) logarithm, base 10 max(value 1, value 2) larger of two values min(value 1, value 2) smaller of two values pow(base, exponent) base to the exponent power random() random double between 0 and 1 range [0. 0, 1. 0) round(value) nearest whole number sin(value) sine, in radians sqrt(value) square root 22
Methods that return values • return: To send a value out as the result of a method, which can be used in an expression. – A return is like the opposite of a parameter: • Parameters pass information in from the caller to the method. • Return values pass information out from a method to its caller. Math. abs -42 42 main 2. 71 3 Math. round – The Math methods do not print results to the console. Instead, each method evaluates to produce (or return) a numeric 23 result, which can be used in an expression.
• Math method call syntax: Math. <method name> ( <parameter(s)> ) • Examples: double square. Root = Math. sqrt(121. 0); System. out. println(square. Root); // 11. 0 int absolute. Value = Math. abs(-50); System. out. println(absolute. Value); // 50 System. out. println(Math. min(3, 7)+2); //5 – Notice that the preceding calls are used in expressions; they can be printed, stored into a variable, etc. 24
• Evaluate the following expressions: – Math. abs(-1. 23) – Math. pow(3, 2) – Math. pow(10, -2) – Math. sqrt(121. 0) - Math. sqrt(256. 0) – Math. round(Math. PI) + Math. round(Math. E) – Math. ceil(6. 022) + Math. floor(15. 9994) – Math. abs(Math. min(-3, -5)) • Math. max and Math. min can be used to bound numbers. Consider an int variable named age. – What statement would replace negative ages with 0? age = (age + Math. abs(age)) / 2; – What statement would cap the maximum age to 40? age = Math. min(age, 40); 25
26
27
• Syntax for writing your own methods that return a value: public static <type> <name> ( < parameter(s)> ) { < statement(s)> ; } – Returning a value from a method: return <expression> ; • Example: // Returns the slope of the line between the given points. public static double slope(int x 1, int y 1, int x 2, int y 2) { double dy = y 2 - y 1; double dx = x 2 - x 1; return dy / dx ; } • Example call: double my. Slope = slope(3, 9, 12, 22); System. out. println("The slope = " + my. Slope); Output: The slope = 1. 44444444 28
29
Return examples // Converts Fahrenheit to Celsius. public static double f. To. C(double degrees. F) { double degrees. C = 5. 0 / 9. 0 * (degrees. F - 32); return degrees. C; } // Computes length of triangle hypotenuse given its side lengths. public static double hypotenuse(int a, int b) { double c = Math. sqrt(a * a + b * b); return c; } // Rounds the given number to two decimal places. // Example: round(2. 71828183) returns 2. 72. public static double round 2(double value) { } double result return result = value * 100; = Math. round(result); = result / 100; result; // upscale the number // round to nearest integer // downscale the number 30
Return examples shortened // Converts Fahrenheit to Celsius. public static double f. To. C(double degrees. F) { return 5. 0 / 9. 0 * (degrees. F - 32); } /* Computes length of triangle hypotenuse given its side lengths. */ public static double hypotenuse(int a, int b) { return Math. sqrt(a * a + b * b); } // Rounds the given number to two decimal places. // Example: round(2. 71828183) returns 2. 72. public static double round 2(double value) { return Math. round(value * 100) / 100; } 31
Return questions • Write a method named area that accepts a circle's radius as a parameter and returns its area. – You may wish to use the constant Math. PI in your solution. • Write a method named distance. From. Origin that accepts x and y coordinates as parameters and returns the distance between that (x, y) point and the origin. • Write a method named attendance that accepts a number of lectures attended by a student, and returns how many points a student receives for attendance. The student receives 2 points for each of the first 5 lectures attended and 1 point for each subsequent lecture. 32
How to comment methods with parameters • If your method accepts parameters and/or returns a value, write a brief description of what the parameters are used for and what kind of value will be returned. – In your comments, you can also write your assumptions about the values of the parameters. – You may wish to give examples of what values your method returns for various input parameter values. – Example: // This method returns the factorial of the given integer n. // The factorial is the product of all integers up to that number. // Assumes that the parameter value is non-negative. // Example: factorial(5) returns 1 * 2 * 3 * 4 * 5 = 120. public static int factorial(int n) {. . . } 33
Method Overloading • You can write methods so that both of the following work: draw. Box(8, 10); and draw. Box(); public static void draw. Box (int x, int y) { { // draws a box x places wide and y places tall. …} public static void draw. Box () { { // draws a box of default size, say 5 by 5 draw. Box(5, 5); } • These methods differ in their Signatures, the number and/or types of their parameters. The compiler looks for the definition of a method named draw. Box that has 2 integer parameters in the first case and no parameters in the second. As far as the compiler is concerned these are completely different methods. 34
Method Overloading: Having more than one method with the same name, but different parameters. public static void main(String[] args) { draw. Block(); draw. Block('C'); draw. Block('A'); draw. Block('T'); draw. Block(); } public static void draw. Block() { System. out. println("+-+"); System. out. println("| |"); System. out. println("+-+"); } public static void draw. Block(char c) { System. out. println("+-+"); System. out. println("|" + c + "|"); System. out. println("+-+"); } +-+ | | +-+ |C| +-+ |A| +-+ |T| +-+ | | +-+ 35
More precisely: A Method Signature is the name of a method along with the number of its parameters and the types of those parameters. Method Overloading occurs when more than one method have the same name. They must have different signatures! Example: Definitions of methods within System. out. println(String s) System. out. println(boolean b) System. out. println(char c) System. out. println(int i) System. out. println(double d). . . 36
Section 3. 3 Using Objects So far, we have seen: methods, which represent code to do something variables, which represent data (categorized by types) It is possible to create new types that contain both variables and methods. Such types are called object types. Languages such as Java in which you can do this are called object-oriented programming languages. In Chapter 3 we start learning how to use some of Java's built in objects. In Chapter 8 we will learn to create our own types of objects.
class: • The code that declares a group of variables and the associated methods for manipulating those variables. • A class is a template from which objects are built. • A class has no physical existence, it occupies no space in memory. (int itself occupies no space, int x; x occupies space. ) • Java contains many predefined classes § Examples: o The class String represents objects that store text characters and has methods for searching and selecting. o The class Point represents objects that store (x, y) data and has methods for calculating distance, and moving. o The class Color represents objects that hold the amounts of reg, green, and blue in a color and has methods for brightening and darkening • A class is a new type that you can define to do what you want it to do.
object: A particular instance of a class. An object occupies space in memory. An object’s contents are defined by its class. An object contains data and behavior. • There are variables inside the object, representing its data. • There are methods inside the object, representing its behavior. 39
Most objects are constructed with the new keyword. <type> <name> = new <type> ( <parameters> ); Examples: Point pt = new Point(7, -4); Color orange = new Color(255, 128, 0); Drawing. Panel p = new Drawing. Panel(300, 200); Convention: class names start with a capital letter (e. g. Point) Strings are also objects, but are constructed without new : String name = "Amelia Bedelia";
41
Examples: • The Math class contains the methods for sqrt, abs, log, etc. Math is a little different than other classes in that you never instantiate an object of type Math. • The class String represents objects that store text characters and contains methods that perform operations on objects of type String my. String = “This is a string”; // Creates a String object System. out. println(my. String); // prints: This is a string length() is method that returns the length of the string. int my. String. Length; my. String. Length = my. String. length(); // my. String. Length is 16 42
Constructing objects • construct: To create a new object. – Objects are constructed with the new keyword. – Most objects must be constructed before they can be used. • Constructing objects, general syntax: <type> <name> = new <type> ( <parameters> ); – Examples (that are not expected to be completely understandable right now): Point p = new Point(7, -4); Drawing. Panel window = new Drawing. Panel(300, 200); Color orange = new Color(255, 128, 0); – Classes' names are usually uppercase (e. g. Point, Color). – Strings are also objects, but are constructed without new : String name = "Amanda Ann Camp"; 43
• Objects contain methods that can be called by your program. – For example, a String's methods manipulate or process text in that String in useful ways. – When we call an object's method, we are sending a message to it. – We must specify which object we are talking to, and then write the method's name. • Calling a method of an object, general syntax: <object>. <method name> ( <parameters> ) 44
– Examples: String my. Dogs = “Corky and Meg"; System. out. println(my. Dogs. length()); // 13 Point p 1 = new Point(3, 4); Point p 2 = new Point(0, 0); double how. Far = p 1. distance(p 2)); //how. Far = 5. 0 Why? 45
46
Data stored in each Point object: Field name x y Description the point's x-coordinate the point's y-coordinate Useful methods of Point objects: Method name Description distance(p) how far away the point is from point p set. Location(x, y) sets the point's x and y to the given values translate(dx, dy) adjusts the point's x and y by given amounts
Point objects can also be printed using println statements: Point p = new Point(5, -2); System. out. println(p); Output: java. awt. Point[x=5, y=-2] • System. out. println(p. x “ “ + p. y); Output: 5 -2 • Point p 1 = new Point(3, 4); Point p 2 = new Point(0, 0); double how. Far = p 1. distance(p 2)); //how. Far = 5. 0 // Why? 48
String indexing Given String greedy = “This is mine. ”; T h i s mi n e . 0 1 2 3 4 5 6 7 8 9 10 11 12 characters indices Each character in the string is stored at a place numbered from 0 to the length of the string -1. This number is called its index. There is a String method named char. At() that returns the character at a specific index in the string. char 7 = greedy. char. At(6); // char 7 contains ‘s’. 49
String methods • Given the following string: String book = "Building Java Programs"; How would you extract the word "Java" ? book. substring(9, 13) How would you change book to store: "BUILDING JAVA PROGRAMS" ? book=book. to. Upper. Case(); – How would you extract the first word from any general string? my. String. substring(0, my. String. index. Of(“ “)) Method name char. At(index) Description character at a specific index. Of(str) index where the start of the given string appears in this string (-1 if it is not there) length() number of characters in this string substring(index 1, index 2) the characters in this string from index 1 (inclusive) to index 2 (exclusive) to. Lower. Case() a new string with all lowercase letters to. Upper. Case() a new string with all uppercase letters 50
String method examples // 11 // index 012345678901 String s 1 = "Stuart Reges"; String s 2 = "Marty Stepp"; System. out. println(s 1. length()); System. out. println(s 1. index. Of("e")); System. out. println(s 1. substring(1, 4)); // 12 // 8 // tua String s 3 = s 2. to. Upper. Case(); System. out. println(s 3. substring(6, 10)); // STEP String s 4 = s 1. substring(0, 6); System. out. println(s 4. to. Lower. Case()); // stuart
The String type is called immutable because Strings can not be modified! The methods that appear to modify a string: substring, to. Lower. Case, to. Upper. Case, . . . actually create and return a new string. String s = "I am immutable"; s. to. Upper. Case(); System. out. println(s); // output: I am immutable If you want to modify the variable, you must reassign it to store the result of the method call: String s = "I am immutable"; s = s. to. Upper. Case(); System. out. println(s); // output: I AM IMMUTABLE
Common error - Not using the result of a method call Ex. book. to. Upper. Case(); // Legal Java statement Returns the string "BUILDING JAVA PROGRAMS" but does not change the object book. Need to say book = book. to. Upper. Case(); This replaces the string in book with the result of calling book. to. Upper. Case(). e. g. , i + 1; does not change i but i = i + 1; does 53
• Reference semantics With primitive types, the value of the variable is stored in the place given by that variable’s name. int x = 8; // x 8 With objects, the place in memory named by that object does not contain the objects value but a reference (memory address) of the place that actually stores the object. String greedy = “This is mine. ”; // greedy This is mine. • Efficiency and sharing It is frequently adequate (or even preferred) to share an object rather than having multiple copies of it. References allow this. String share = greedy; // share The reference value in greedy is copied into share. 54
Objects are stored differently than primitive types. Primitive types are stored directly in memory. Objects are stored elsewhere in a 7 memory and the associated variable pt contains a reference to that location. int a = 7; Point pt = new Point(9, 20); Point { 9 20 Memory
Java organizes groups of related classes into Packages To use Point, you need to know that it is in the "Abstract Windows Toolkit" package and put at the start of your program: import java. awt. *; public class Draw. Picture { public static void main(String[] args) { Point start = new Point(0, 0); Point finish = new Point(40, 20); int dist = start. distance(finish); . . . } }
When you copy a primitive type, it copies the value. When you copy an object, it copies the reference. The contents of the place in memory Memory are always copied. In one case it is a value and in the other is a reference. int a Point b Point = 7; pt 1 = new Point(9, 20); = a; pt 2 = pt 1; a pt 1 b pt 2 { Point 7 7 9 20
The same thing happens when you pass parameters to a method. When you pass a primitive type, it copies the value. When you pass an object, it copies the reference. int a = 7; Point pt 1 = new Point(9, 20); moo(a, pt 1); . . . public static int moo(int b, Point pt 2) {. . . Memory a pt 1 7 b pt 2 7 { Point 9 20
Activity: What does this code print? public static void main(String[] args) { int a = 7; Point pt 1 = new Point(10, 15); Point pt 2 = new Point(30, 40); pt 2 = mystery(a, pt 1); System. out. println("a= " + a); System. out. println(pt 1); System. out. println(pt 2); } public static Point mystery(int c, Point pt 3) { c += 3; a= 7 pt 3. translate(c, c); java. awt. Point[x=20, y=25] java. awt. Point[x=25, y=20] Point pt 4 = new Point(pt 3. y, pt 3. x); return pt 4; }
Section 3. 4 Interactive programs using Scanner objects Interactive programs • We have written programs that print console output. • It is also possible to read input from the console. – The user types the input into the console. – We can capture the input and use it in our program. – Such a program is called an interactive program. • Interactive programs can be challenging: – Computers and users think in very different ways. – Users tend to make errors. 60
• We print output using an object named System. out – This object has methods named println and print. • We read input using an object named System. in – System. in is not intended to be used directly. – We will use a second object, from a class called Scanner, to help us read input from System. in. • Constructing a Scanner object to read console input: Scanner <name> = new Scanner(System. in); – Example: Scanner console = new Scanner(System. in) – Once we have constructed the Scanner, we call various methods on it to read the input from the user. 61
• Methods of Scanner that we will use in this chapter: Method Description next. Int() reads and returns an int value next. Double() reads and returns a double value next() reads and returns the next token as a String next. Line() reads and returns the next line of input as a String – Each of these methods pauses your program until the user types input and presses Enter. • Then the value typed is returned to your program. • Usually you use an assignment statement to put the value into a variable. e. g. int age = console. next. Int(); if you type a 6 on the Console, age will be set to 6. 62
Scanner is in a package named java. util To use Scanner, put import java. util. *; at the start of your program. import java. util. *; import java. awt. *; public class Plot. Points { public static void main(String[] args) { Scanner console = new Scanner(System. in); System. out. print("Enter the X Y coordinates? "); int x = console. next. Int(); int y = console. next. Int(); Point start = new Point(x, y); . . . Console: Enter the X Y coordinates? 10 24
– prompt: A message printed to the user, telling them what input to type, before we read from the Scanner. • Example: System. out. print("How old are you? "); // prompt int age = console. next. Int(); System. out. println("You'll be 40 in " + (40 - age) + " years. "); • Output (user input underlined): How old are you? 24 You’ll be 40 in 16 years. If there is no prompt, the cursor will just sit there blinking at you. Click in the Console before entering input, otherwise it may go into the edit window. 64
• Java class libraries: A large set of Java classes available for you to use (part of the JDK). – These objects are organized into groups named packages. – To use the objects from a package, you must include an import declaration at the top of your program. • Import declaration, general syntax: import <package name>. *; • Scanner is in a package named java. util – To use Scanner, put this at the start of your program: import java. util. *; 65
Example of scanner usage: import java. util. *; // so that we can use Scanner public class Read. Some. Input { public static void main(String[] args) { Scanner console = new Scanner(System. in); System. out. print("What is your first name? "); String name = console. next(); System. out. print("And how old are you? "); int age = console. next. Int(); System. out. println(name + " is " + age); System. out. println("That's quite old!"); }} Output (user input underlined): What is your first name? Ruth How old are you? 14 Ruth is 14 That's quite old
• Input token: A unit of user input, as read by the Scanner. – Tokens are separated by whitespace (spaces, tabs, new lines). – How many tokens appear on the following line of input? 23 John Smith 42. 0 "Hello world" Ans: 6. . . 67
Another Scanner example: import java. util. *; // so that we can use Scanner public class Average { public static void main(String[] args) { Scanner console = new Scanner(System. in); System. out. print("Please type three numbers: "); int num 1 = console. next. Int(); int num 2 = console. next. Int(); int num 3 = console. next. Int(); double average = (double) (num 1 + num 2 + num 3) / 3; System. out. println("The average is " + average); } } Output (user input underlined): Please type three numbers: 8 6 13 The average is 9. 0 Notice that the Scanner can read multiple values from one line.
• When the token doesn't match the type the Scanner tries to read, the program crashes. Example: System. out. print("What is your age? "); int age = console. next. Int(); Output (user's input is underlined): What is your age? Timmy Exception in thread "main" java. util. Input. Mismatch. Exception at java. util. Scanner. throw. For(Unknown Source) at java. util. Scanner. next. Int(Unknown Source) at Read. Tokens. main(Read. Tokens. java: 11) 69
Example: import java. util. *; // so that I can use Scanner public class Read. Some. Input { public static void main(String[] args) { Scanner console = new Scanner(System. in); System. out. print("What is your first name? "); String name = console. next(); System. out. print("And how old are you? "); int age = console. next. Int(); System. out. println(name + " is " + age); System. out. println("That's quite old!"); }} • Output (user input underlined): What is your first name? Ruth How old are you? 14 Ruth is 14 That's quite old! 70
Example: import java. util. *; // so that I can use Scanner public class Average { public static void main(String[] args) { Scanner console = new Scanner(System. in); System. out. print("Please type three numbers: "); int num 1 = console. next. Int(); int num 2 = console. next. Int(); int num 3 = console. next. Int(); double average = (double) (num 1 + num 2 + num 3) / 3; System. out. println("The average is " + average); }} • Output (user input underlined): Please type three numbers: 8 6 13 The average is 9. 0 – Notice that the Scanner can read multiple values from one line. – Extra white space also makes no difference. Values could be on separate lines. 71
• If multiple methods read user input, declare a Scanner in main and pass it to each of them as a parameter. – In this way, all of the methods share the same Scanner object. public static void main(String[] args) { Scanner console = new Scanner(System. in); int sum = read. Sum 3(console); System. out. println("The sum is " + sum); } public static int read. Sum 3(Scanner console) { System. out. print("Type 3 numbers: "); int num 1 = console. next. Int(); int num 2 = console. next. Int(); int num 3 = console. next. Int(); return num 1 + num 2 + num 3; } 72
// This program computes two people's body mass index (BMI) // and compares them. The code uses parameters and returns. import java. util. *; // so that I can use Scanner public class BMI { public static void main(String[] args) { introduction(); Scanner console = new Scanner(System. in); double bmi 1 = process. Person(console); double bmi 2 = process. Person(console); } // report overall results System. out. println("Person #1 body mass index = " + bmi 1); System. out. println("Person #2 body mass index = " + bmi 2); double difference = Math. abs(bmi 1 - bmi 2); System. out. println("Difference = " + difference); // prints a welcome message explaining the program public static void introduction() { System. out. println("This program reads in data for two people"); System. out. println("and computes their body mass index (BMI)"); System. out. println("and weight status. "); System. out. println(); }. . . 73
. . . // reads info for a person, computes their BMI, and returns it public static double process. Person(Scanner console) { System. out. println("Enter next person's information: "); System. out. print("height (in inches)? "); double height = console. next. Double(); System. out. print("weight (in pounds)? "); double weight = console. next. Double(); System. out. println(); double bmi = get. BMI(height, weight); return bmi; } // Computes a person's body mass index based on their height // and weight and returns the BMI as its result. public static double get. BMI(double height, double weight) { double bmi = weight / (height * height) * 703; return bmi; } } 74
This program reads in data for two people and computes their body mass index (BMI) and weight status. Enter next person's information: height (in inches)? 75 weight (in pounds)? 195 Enter next person's information: height (in inches)? 77 weight (in pounds)? 145 Person #1 body mass index = 24. 3706666665 Person #2 body mass index = 17. 19261258222297 Difference = 7. 178054084443694 Scanner remembers where the input pointer is. 75
main: Scanner console = new Scanner(System. in); Console scanner. Position: before the 1 st input Just entered the process. Person method If the Scanner object (console) were not passed, a new Scanner object would be instantiated (using new) here. System. out. println("Enter next person's information: "); System. out. print("height (in inches)? "); Enter next person's information: height (in inches)? 76
double height = console. next. Double(); Console scanner. Position: directly after the first input Enter next person's information: height (in inches)? 75 // just read first person’s height 77
double weight = console. next. Double(); Console scanner. Position: directly after the second input Enter next person's information: height (in inches)? 75 weight (in pounds)? 195 // just read the first person’s weight 78
Enter the process. Person method the second time Console scanner. Position: directly after the third input If the Scanner object (console) were not passed, a new Scanner object would be instantiated (using new) here. The input position would be lost and it would start at the beginning again. System. out. println("Enter next person's information: "); System. out. print("height (in inches)? "); double height = console. next. Double(); Enter next person's information: height (in inches)? 75 weight (in pounds)? 195 Enter next person's information: height (in inches)? 77 // just read the second person’s height 79
double height = console. next. Double(); Console scanner. Position: directly after the fourth input Enter next person's information: height (in inches)? 75 weight (in pounds)? 196 Enter next person's information: height (in inches)? 77 weight (in pounds)? 145 // just read the second person’s height 80
System. out. println(“Enter a one line quote: “; String quote = console. next. Line(); Console Enter a one line quote: Twenty years of schoolin’ and they put you on the day shift. After executing the assignment operator, quote Twenty years of schoolin’ and they put you on the day shift. 81
import java. util. *; public class All. In. One { public static void main(String[] args) { Scanner console = new Scanner(System. in); System. out. print("Find the sum of integersnfrom: "); int low = console. next. Int(); System. out. print("to: "); int high = console. next. Int(); System. out. println("The sum of the integers from " + low + " to " + high + " is " + int. Sum(low, high)); System. out. println("By finding sum(1, " + high + ") minus sum(1, " + (low - 1) + "), the sum is " + (int. Sum(high) - int. Sum(low - 1))); } Find the sum of integers from: 50 to: 100 The sum of the integers from 50 to 100 is 3825. 0 By finding sum(1, 100) minus sum(1, 49), the sum is 3825. 0 82
public static double int. Sum(int small, int big) { double sum = 0. 0; for ( int i = small; i <= big ; i++) sum = sum + i; return sum; } public static double int. Sum(int value){ double sum = 0. 0; for ( int i = 1; i <= value; i++) { sum = sum + i; } return sum; } } 83
Math. random() returns a random double value in the range [0. 0, 1. 0). In English this says it returns a random value in the range from 0. 0 (including 0. 0, or inclusive) and 1. 0 (not including 1. 0, or exclusive). Thus, the range is 0. 0 through 0. 99999…. (This is needed in Assignment 4. ) Often we want a value that is an integer in a certain range. Say want a value in the range [1, 10]. Would the following return a value of 1 to 10, inclusive? (int) (Math. random() * 10); // no, returns a value in the range 0 to 9 Why? Math. random() returns a value in the range 0. 0 through 9. 9999. When that is cast to an int, we get a value in the range 0 through 9. What can we do? Add 1. int One. To 10 = (int) (Math. random() * 10) + 1; // One. To 10 has a value in // the range [1, 10]. 84
Assume we have a string of 4 characters, e. g. String my. String = “cave”; c a v e 0 1 2 3 We can generate a String with those letters in reverse by using The empty String rev. String = “” + my. String. char. At(3) + my. String. char. At(2) + my. String. char. At(1) + my. String. char. At(0); The above assignment yields the following character from each of the my. String. char. At() method calls. rev. String = “” + ‘e’ + ‘v’ + ‘a’ + ‘c’; e v a c 0 1 2 3 When working with Strings, initializing to “” (the empty string) is as common as initializing an int to 0 or 1. 85
- Slides: 85