Building Java Programs Chapter 3 Introduction to Parameters
Building Java Programs Chapter 3: Introduction to Parameters and Objects Copyright 2006 by Pearson Education 1
Chapter outline n parameters n n n methods that return values n n n passing parameters to static methods writing methods that accept parameters calling methods that return values (e. g. the Math class) writing methods that return values using objects n n n String objects Point objects console input with Scanner objects Copyright 2006 by Pearson Education 2
Parameters reading: 3. 1 Copyright 2006 by Pearson Education 3
Reminder: class constants n In the last chapter, we used class constants to fix "magic number" redundancy problems: public static final int FIGURE_WIDTH = 5; public static void draw. Figure 1() { draw. Plus. Line(); draw. Bar. Line(); draw. Plus. Line(); } public static void draw. Plus. Line() { System. out. print("+"); for (int i = 1; i <= FIGURE_WIDTH; i++) { System. out. print("/\"); } System. out. println("+"); } public static void draw. Bar. Line() { System. out. print("|"); for (int i = 1; i <= 2 * FIGURE_WIDTH; i++) { System. out. print(" "); } System. out. println("|"); } Copyright 2006 by Pearson Education 4
Another repetitive figure n Now consider the task of drawing the following figures: ********************* ***** * * ***** n The lines and figures are similar, but not exactly the same. Copyright 2006 by Pearson Education 5
A redundant solution 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(); } public static void draw. Line. Of 13 Stars() { for (int i = 1; i <= 13; i++) { System. out. print("*"); } System. out. println(); } public static void draw. Line. Of 7 Stars() { for (int i = 1; i <= 7; i++) { System. out. print("*"); } System. out. println(); } n n n The methods at left are redundant. Would constants help us solve this problem? What would be a better solution? n n draw. Line - A method to draw a line of any number of stars. draw. Box - A method to draw a box of any size. public static void draw. Line. Of 35 Stars() { for (int i = 1; i <= 35; i++) { System. out. print("*"); } System. out. println(); }. . . Copyright 2006 by Pearson Education 6
Parameterization n parameterized method: One that is given extra information (e. g. number of stars to draw) when it is called. n parameter: A value passed to a method by its caller. n Writing parameterized methods requires 2 steps: n n write the method to accept the parameter call the method and pass the parameter value(s) desired main 7 13 Copyright 2006 by Pearson Education draw. Line ************* 7
Writing parameterized methods n Parameterized method declaration syntax: public static void <name> ( <type> <name> ) { <statement(s)> ; } n Example: public static void print. Spaces(int count) { for (int i = 1; i <= count; i++) { System. out. print(" "); } } n Whenever print. Spaces is called, the caller must specify how many spaces to print. Copyright 2006 by Pearson Education 8
Calling parameterized methods n n passing a parameter: Calling a parameterized method and specifying a value for its parameter(s). Parameterized method call syntax: <name> ( <expression> ); n Example: System. out. print("*"); print. Spaces(7); System. out. print("**"); int x = 3 * 5; print. Spaces(x + 2); System. out. println("***"); Output: * ** Copyright 2006 by Pearson Education *** 9
How parameters are passed n When the parameterized method call executes: n n the value written 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); } 13 7 public static void print. Spaces(int count) { for (int i = 1; i <= count; i++) { System. out. print(" "); } } Copyright 2006 by Pearson Education 10
Value semantics n value semantics: When primitive variables (int, double) are passed as parameters, their values are copied. n 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); . . . } public static void strange(int x) { x = x + 1; System. out. println("1. x = " + x); } Copyright 2006 by Pearson Education // unchanged Output: 1. x = 24 2. x = 23 11
Common errors n If a method accepts a parameter, it is illegal to call it without passing any value for that parameter. print. Spaces(); n The value passed to a method must be of the correct type, matching the type of its parameter variable. print. Spaces(3. 7); n // ERROR: parameter value required // ERROR: must be of type int Exercise: Change the Stars program to use a parameterized static method for drawing lines of stars. Copyright 2006 by Pearson Education 12
Stars solution // 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(); } } Copyright 2006 by Pearson Education 13
Multiple parameters n Methods can accept multiple parameters. n n n 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)> ; } n Multiple parameters call syntax: <name> ( <expression>, . . . , <expression> ); Copyright 2006 by Pearson Education 14
Multiple parameters example 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 n Exercise: Write an improved Stars program that draws boxes of stars using parameterized static methods. Copyright 2006 by Pearson Education 15
Stars solution // Prints several lines and boxes made of stars. // Third version with 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(); }. . . Copyright 2006 by Pearson Education 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(" "); } } Copyright 2006 by Pearson Education 17
Parameter "mystery" problem n What is the output of the following program? public class Mystery { public static void main(String[] args) { int x = 5, y = 9, z = 2; mystery(z, y, x); System. out. println(x + " " + y + " " + z); mystery(y, x, z); System. out. println(x + " " + y + " " + z); } public static void mystery(int x, int z, int y) { x++; y = x - z * 2; x = z + 1; System. out. println(x + " " + y + " " + z); } } Copyright 2006 by Pearson Education 18
Parameter question n Rewrite the following program to use parameterized methods: // Draws triangular figures of stars. public class Loops { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i - 1; j++) { System. out. print(" "); } for (int j = 1; j <= 10 - 2 * i + 1; j++) { System. out. print("*"); } System. out. println(); } for (int i = 1; i <= 12; i++) { for (int j = 1; j <= i - 1; j++) { System. out. print(" "); } for (int j = 1; j <= 25 - 2 * i; j++) { System. out. print("*"); } System. out. println(); } } } Copyright 2006 by Pearson Education 19
Parameter answer n Rewrite the following program to use parameterized methods: // Draws triangular figures using parameterized methods. public class Loops { public static void main(String[] args) { triangle(5); triangle(12); } // Draws a triangle figure of the given size. public static void triangle(int height) { for (int i = 1; i <= height; i++) { print. Spaces(i - 1); draw. Line(2 * height + 1 - 2 * i); } } } . . . Copyright 2006 by Pearson Education 20
Parameter questions n Write a method named print. Diamond that accepts a height as a parameter and prints a diamond figure: * ***** * n n Write a method named multiplication. Table that accepts a maximum integer as a parameter and prints a table of multiplication from 1 x 1 up to that integer times itself. Write a method named bottles. Of. Beer that accepts an integer as a parameter and prints the "XX Bottles of Beer" song with that many verses. Copyright 2006 by Pearson Education 21
Methods that return values reading: 3. 2 Copyright 2006 by Pearson Education 22
Java's Math class n Java has a class named Math with useful static methods and constants for performing calculations. Method name Description Constant Description abs(value) absolute value E 2. 7182818. . . ceil(value) rounds up PI 3. 1415926. . . 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 round(value) nearest whole number sin(value) sine, in radians sqrt(value) square root Copyright 2006 by Pearson Education 23
Methods that return values n return: To send a value out as the result of a method, which can be used in an expression. n A return is like the opposite of a parameter: n n 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 n Math. round The Math methods do not print results to the console. Instead, each method evaluates to produce (or return) a numeric result, which can be used in an expression. Copyright 2006 by Pearson Education 24
Math method examples n Math method call syntax: Math. <method name> ( <parameter(s)> ) n Examples: n 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. Copyright 2006 by Pearson Education 25
Math method questions n Evaluate the following expressions: n n n n 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. n n What statement would replace negative ages with 0? What statement would cap the maximum age to 40? Copyright 2006 by Pearson Education 26
Methods that return values n Syntax for methods that return a value: public static <type> <name> ( < parameter(s)> ) { < statement(s)> ; } n Returning a value from a method: return <expression> ; n Example: // Returns the slope public static double dy = y 2 double dx = x 2 return dy / dx ; } Copyright 2006 by Pearson Education of the line between the given points. slope(int x 1, int y 1, int x 2, int y 2) { y 1; x 1; 27
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 = value * 100; // upscale the number result = Math. round(result); // round to nearest integer result = result / 100; // downscale the number return result; } Copyright 2006 by Pearson Education 28
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; } Copyright 2006 by Pearson Education 29
Return questions n Write a method named area that accepts a circle's radius as a parameter and returns its area. n n n 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 and 1 point for each subsequent lecture. Copyright 2006 by Pearson Education 30
How to comment: params n 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. n n n 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) {. . . } Copyright 2006 by Pearson Education 31
Using objects reading: 3. 3 Copyright 2006 by Pearson Education 32
Objects n So far, we have seen: n n n It is possible to create new types that are combinations of the existing types. n n n methods, which represent behavior variables, which represent data (categorized by types) Such types are called object types or reference types. Languages such as Java in which you can do this are called object-oriented programming languages. We will learn how to use some of Java's objects. n In Chapter 8 we will learn to create our own types of objects. Copyright 2006 by Pearson Education 33
Objects and classes n object: An entity that contains data and behavior. n n There are variables inside the object, representing its data. There are methods inside the object, representing its behavior. n class: A program, or a template for a type of objects. n Examples: n n n The class String represents objects that store text characters. The class Point represents objects that store (x, y) data. The class Scanner represents objects that read information from the keyboard, files, and other sources. Copyright 2006 by Pearson Education 34
Constructing objects n n construct: To create a new object. n Objects are constructed with the new keyword. n Most objects must be constructed before they can be used. Constructing objects, general syntax: <type> <name> = new <type> ( <parameters> ); n n n Examples: 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"; Copyright 2006 by Pearson Education 35
Calling methods of objects n Objects contain methods that can be called by your program. n n For example, a String's methods manipulate or process the text of 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: <variable>. <method name> ( <parameters> ) n n The results will be different from one object to another. Examples: String gangsta = "G. , Ali"; System. out. println(gangsta. length()); // 7 Point p 1 = new Point(3, 4); Point p 2 = new Point(0, 0); System. out. println(p 1. distance(p 2)); // 5. 0 Copyright 2006 by Pearson Education 36
Point objects n Java has a class of objects named Point. n n To use Point, you must write: import java. awt. *; Constructing a Point object, general syntax: Point <name> = new Point(<x>, <y>); Point <name> = new Point(); // the origin, (0, 0) n n Examples: Point p 1 = new Point(5, -2); Point p 2 = new Point(); Point objects are useful for several reasons: n n They store two values, an (x, y) pair, in a single variable. They have useful methods we can call in our programs. Copyright 2006 by Pearson Education 37
Point data and methods n Data stored in each Point object: Field name n Description x the point's x-coordinate y the point's y-coordinate Useful methods of each Point object: 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 the given amounts n Point objects can also be printed using println statements: Point p = new Point(5, -2); System. out. println(p); // java. awt. Point[x=5, y=-2] Copyright 2006 by Pearson Education 38
Using Point objects n An example program that uses Point objects: import java. awt. *; public class Point. Main { public static void main(String[] args) { // construct two Point objects Point p 1 = new Point(7, 2); Point p 2 = new Point(4, 3); // print each point and their distance apart System. out. println("p 1 is " + p 1); System. out. println("p 2: (" + p 2. x + ", " + p 2. y + ")"); System. out. println("distance = " + p 1. distance(p 2)); // translate the point to a new location p 2. translate(1, 7); System. out. println("p 2: (" + p 2. x + ", " + p 2. y + ")"); System. out. println("distance = " + p 1. distance(p 2)); } } Copyright 2006 by Pearson Education 39
Point objects question n Write a program that computes a right triangle's perimeter. n The perimeter is the sum of the triangle's side lengths a+b+c. n Read values a and b and compute side length c as the distance between the points (0, 0) and (a, b). side a? 12 side b? 5 perimeter is 30. 0 Copyright 2006 by Pearson Education 40
Point objects answer import java. awt. *; import java. util. *; // for Point // for Scanner public class Triangle. Perimeter { public static void main(String[] args) { Scanner console = new Scanner(System. in); System. out. print("side a? "); int a = console. next. Int(); System. out. print("side b? "); int b = console. next. Int(); Point p 1 = new Point(); // 0, 0 Point p 2 = new Point(a, b); double c = p 1. distance(p 2); double perimeter = a + b + c; System. out. println("perimeter is " + perimeter); } } Copyright 2006 by Pearson Education 41
Objects as parameters: value vs. reference semantics reading: 3. 3 Copyright 2006 by Pearson Education 42
Swapping primitive values n Consider the following code to swap two int variables: public static void main(String[] args) { int a = 7; int b = 35; System. out. println(a + " " + b); // swap a with b a = b; b = a; System. out. println(a + " " + b); } n What is wrong with this code? What is its output? Copyright 2006 by Pearson Education 43
Swapping, corrected n When swapping, you should set aside one variable's value into a temporary variable, so it won't be lost. n Better code to swap two int variables: public static void main(String[] args) { int a = 7; int b = 35; System. out. println(a + " " + b); // swap a with b int temp = a; a = b; b = temp; System. out. println(a + " " + b); } Copyright 2006 by Pearson Education 44
A swap method? n Swapping is a common operation, so we might want to make it into a method. n Does the following swap method work? Why or why not? public static void main(String[] args) { int a = 7; int b = 35; System. out. println(a + " " + b); // swap a with b swap(a, b); } System. out. println(a + " " + b); public static void swap(int a, int b) { int temp = a; a = b; b = temp; } Copyright 2006 by Pearson Education 45
Value semantics n value semantics: Behavior where variables are copied when assigned to each other or passed as parameters. n n Primitive types in Java use value semantics. When one variable is assigned to another, the value is copied. Modifying the value of one variable does not affect others. Example: int y = x = 5; y = x; 17; 8; // x = 5, y = 5 // x = 5, y = 17 // x = 8, y = 17 x Copyright 2006 by Pearson Education y 46
Modifying primitive parameters n When we call a method and pass primitive variables' values as parameters, we can assign new values to the parameters inside the method. n n But this does not affect the value of the variable that was passed; its value was copied, and the two variables are otherwise distinct. Example: public static void main(String[] args) { int x = 1; x 1 foo(x); System. out. println(x); // output: 1 } public static void foo(int x) { x = 2; x 1 2 } Copyright 2006 by Pearson Education value 1 is copied into parameter's value is changed to 2 (variable x in main is unaffected) 47
Reference semantics n reference semantics: Behavior where variables refer to a common value when assigned to each other or passed as parameters. n n Objects in Java use reference semantics. Object variables do not actually store an object; they store the address of an object's location in the computer memory. n n n Variables for objects are called reference variables. We often draw reference variables as small boxes that point an arrow toward the object they refer to. Example: Point p 1 = new Point(3, 8); p 1 Copyright 2006 by Pearson Education x 3 y 8 48
Multiple references n If two reference variables are assigned to refer to the same object, the object is not copied. n n Both variables literally share the same object. Calling a method on either variable will modify the same object. Point p 1 = new Point(3, 8); Point p 2 = new Point(2, -4); Point p 3 = p 2; p 1 x 3 y 8 p 2 x 2 y -4 p 3 n Here 3 variables refer to 2 objects. If we change p 3, will p 2 change? If we change p 2, will p 3 change? 49 Copyright 2006 by Pearson Education
Multiple references n If two variables refer to the same object, modifying one of them will also make a change in the other: p 3. translate(5, 1); System. out. println("(" + p 2. x + " " + p 2. y + ")"); p 1 x 3 y 8 p 2 x 7 y -3 p 3 OUTPUT: (7, -3) Copyright 2006 by Pearson Education 50
Why references? n The fact that objects are passed by reference was done for several reasons: n n efficiency. Objects can be large, bulky things. Having to copy them every time they are passed as parameters would slow down the program. sharing. Since objects hold important state and have behavior that modifies that state, it is often more desirable for them to be shared by parts of the program when they're passed as parameters. Often we want the changes to occur to the same object. Copyright 2006 by Pearson Education 51
Objects as parameters n When an object is passed as a parameter, the object is not copied. The same object is shared by the original variable and parameter. n If a method is called on the parameter, it will affect the original object that was passed to the method. n Since the variable p 1 and the parameter p refer to the same object, modifying one will also make a change in the other: public static void main(String[] args) { Point p 1 = new Point(2, 3); example(p 1); p 1 } x -1 y -2 public static void example(Point p) { p. set. Location(-1, -2); p } Copyright 2006 by Pearson Education 52
String objects n string: A sequence of text characters. n n n One of the most common types of objects. In Java, strings are represented as objects of class String variables can be declared and assigned, just like primitive values: String <name> = "<text>"; String <name> = <expression that produces a String>; n Unlike most other objects, a String is not created with new. n Examples: String name = "Marla Singer"; int x = 3, y = 5; String point = "(" + x + ", " + y + ")"; Copyright 2006 by Pearson Education 53
Indexes n The characters in a String are each internally numbered with an index, starting with 0: n Example: String name = "P. Diddy"; index 0 character 'P' n 1 2 3 4 5 6 7 '. ' 'D' 'i' 'd' 'y' Individual characters are represented inside the String by values of a primitive type called char. n n Literal char values are surrounded with apostrophe (singlequote) marks, such as 'a' or '4'. An escape sequence can be represented as a char, such as 'n' (new-line character) or ''' (apostrophe). Copyright 2006 by Pearson Education 54
String methods n Useful methods of each String object: Method name char. At(index) n 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 These methods are called using the dot notation: String example = "speak friend and enter"; System. out. println(example. to. Upper. Case()); Copyright 2006 by Pearson Education 55
String method examples // 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()); Copyright 2006 by Pearson Education // stuart 56
Modifying Strings n The methods that appear to modify a string (substring, to. Lower. Case, to. Upper. Case, etc. ) actually create and return a new string. String s = "lil bow wow"; s. to. Upper. Case(); System. out. println(s); // output: lil bow wow n If you want to modify the variable, you must reassign it to store the result of the method call: String s = "lil bow wow"; s = s. to. Upper. Case(); System. out. println(s); // output: LIL BOW WOW Copyright 2006 by Pearson Education 57
String methods n Given the following string: n n n String book = "Building Java Programs"; How would you extract the word "Java" ? How would you change book to store: "BUILDING JAVA PROGRAMS" ? How would you extract the first word from any general string? 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 Copyright 2006 by Pearson Education 58
Interactive programs using Scanner objects reading: 3. 4 Copyright 2006 by Pearson Education 59
Interactive programs n We have written programs that print console output. n It is also possible to read input from the console. n n 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: n n Computers and users think in very different ways. Users tend to misbehave. Copyright 2006 by Pearson Education 60
Input and System. in n We print output using an object named System. out n n We read input using an object named System. in n This object has methods named println and print. 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); n n 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. Copyright 2006 by Pearson Education 61
Scanner methods n Methods of Scanner that we will use in this chapter: Method next. Int() Description reads and returns user input as an int next. Double() reads and returns user input as a double next() reads and returns user input as a String n Each of these methods pauses your program until the user types input and presses Enter. n n n Then the value typed is returned to your program. 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. "); Copyright 2006 by Pearson Education 62
Java class libraries, import n Java class libraries: A large set of Java classes available for you to use (part of the JDK). n n n 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>. *; n Scanner is in a package named java. util n To use Scanner, put this at the start of your program: import java. util. *; Copyright 2006 by Pearson Education 63
Input tokens n token: A unit of user input, as read by the Scanner. n n n 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" 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 java. util. Input. Mismatch. Exception at java. util. Scanner. throw. For(Unknown Source) at java. util. Scanner. next. Int(Unknown Source). . . Copyright 2006 by Pearson Education 64
Example Scanner usage 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!"); } } n Output (user input underlined): What is your first name? Ruth How old are you? 14 Ruth is 14 That's quite old! Copyright 2006 by Pearson Education 65
Another Scanner 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); } } n Output (user input underlined): Please type three numbers: 8 6 13 The average is 9. 0 n Notice that the Scanner can read multiple values from one line. Copyright 2006 by Pearson Education 66
Scanners as parameters n If multiple methods read user input, declare a Scanner in main and pass it to each of them as a parameter. n 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; } Copyright 2006 by Pearson Education 67
Scanner BMI question A person's body mass index (BMI) is computed by the following formula: n Write a program that produces the following output: 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)? 62. 5 weight (in pounds)? 130. 5 Enter next person's information: height (in inches)? 58. 5 weight (in pounds)? 90 Person #1 body mass index = 23. 485824 Person #2 body mass index = 18. 487836949375414 Difference = 4. 997987050624587 Copyright 2006 by Pearson Education 68
Scanner BMI solution // 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(); }. . . Copyright 2006 by Pearson Education 69
Scanner BMI solution, cont. . // reads information for one 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; } Copyright 2006 by Pearson Education 70
- Slides: 70