Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5 - Using Pre-Built Methods

Similar presentations


Presentation on theme: "Chapter 5 - Using Pre-Built Methods"— Presentation transcript:

1 Chapter 5 - Using Pre-Built Methods
1 The API Library API Headings Math Class Wrapper Classes for Primitive Types Lottery Example Character Class String Methods: substring indexOf lastIndexOf Formatted Output with the printf Method 1. In this chapter I demo these files: Lottery.java IdentifierChecker.java

2 The API Library When working on a programming problem, you should normally check to see if there are pre-built classes that meet your program's needs. If there are such pre-built classes, then use those classes (don't "reinvent the wheel"). For example: User input is a rather complicated task. The Scanner class handles user input. Whenever you need user input in a program, use the Scanner class's input methods (rather than writing and using your own input methods). Math calculations are sometimes rather complicated. The Math class handles math calculations. Whenever you need to perform non-trivial math calculations in a program, use the Math class's methods (rather than writing and using your own math methods). 1. In the next chapter, we talk about how to implement your own methods. What's the advantage of using pre-built methods? a) It saves the programmer time. b) The programmer can feel comfortable that the classes have been thoroughly tested and that they work. 2. For example, if you need to find the square root of a number, you should use the Math class's sqrt method. We'll talk about Math methods in detail shortly, but first a couple more API details. 1 2

3 The API Library Java's pre-built classes are stored in its class library, which is more commonly known as the Application Programming Interface (API) library. See Java's API classes are not part of the core Java language. For a program to use an API class, the class first needs to be loaded/imported into the program. For example, to use the Scanner class, include this at the top of your program: import java.util.Scanner; The java.util thing that precedes Scanner is called a package. A package is a group of classes. The java.util package contains quite a few general-purpose utility classes. The only one you'll need for now is the Scanner class. 1 1. I go to Sun's Java API Web site and show the Scanner and Math classes.

4 The API Library Some classes are considered to be so important that the Java compiler automatically imports them for you. The automatically imported classes are in the java.lang package. The Math class is one of those classes, so there's no need for you to import the Math class if you want to perform math operations. The Java compiler automatically inserts this statement at the top of every Java program: import java.lang.*; The asterisk is a wild card and it means that all classes in the java.lang package are imported, not just the Math class. 1 2 1. What do you think lang stands for? language [2. The System class is also in the java.lang package and that's why we don't have to import the System class for Sop statements.]

5 API Headings To use an API class, you don't need to know the internals of the class; you just need to know how to "interface" with it. To interface with a class, you need to know how to use the methods within the class. For example, to perform input, you need to know how to use the Scanner class's methods - next, nextLine, nextInt, nextDouble, etc. To use a method, you need to know what type of argument(s) to pass to it and what type of value it returns. The standard way to show that information is to show the method's source code heading. 1. See the next slide for an example… 1

6 API Headings For example, here's the source code heading for the Scanner class's nextInt method: public int nextInt() And here's an example of calling the nextInt method: int days = stdIn.nextInt(); The arguments that you pass to the method go inside the parentheses (no arguments are passed to the nextInt method). 3 The return type (int in this example) indicates the type of the value that's being returned from the method. 2 1. The public access modifier should look familiar because your main method headings all use public. We'll discuss private methods in Chapter 8; they're accessible only from within the class that defines them. 2. Note the bottom example; nextInt returns an int value and it's stored in an int variable, days. Your main method headings all use void for the return type; void means that the method returns nothing. 3. Note the bottom example; the nextInt call has no arguments inside the parentheses. All the methods in the API library are public, which means that they are accessible from everywhere; i.e., the "public" can access them. 1

7 Math Class 1 Headings for API methods are commonly referred to as API headings. Here are the API headings for some of the more popular methods in the Math class: public static int abs(int num) Returns the absolute value of num. public static double abs(double num) public static int max(int x, int y) Returns the larger value of x and y. public static double max(double x, double y) 2 3 1. Let's now look at some of the Math class's methods. Throughout the book, when there's a need to present a group of methods from the API library, we'll introduce the methods by showing a list of method headings and associated brief descriptions. For example, this slide and the next slide show headings for the important methods within the Math class, and they show associated brief descriptions. We borrowed this method presentation technique from Sun's Java API Web site (see 2. After explaining the abs method, I read through the entire slide after the next slide and return here. 3. The first abs method is for int values. The second one is for double values.

8 Math Class Math class API headings (continued):
public static int min(int x, int y) Returns the smaller value of x and y. public static double min(double x, double y) public static double pow(double num, double power) Returns num raised to the specified power. public static double random() Returns a uniformly distributed value between 0.0 and 1.0, but not including 1.0. public static long round(double num) Returns the whole number that is closest to num. public static double sqrt(double num) Returns the square root of num. 1 1. Note that there's only one pow method, for doubles; there's no pow method for integers. I read the first two bullet items in the slide after the next slide and return here. 2. "Uniformly distributed" means there's the same chance of getting any number within the given range. I read the bottom of the slide after the next slide and return here. 3. How is using round different from using an int type cast operator on a floating-point number? The type cast operator will truncate the fraction whereas the round method will round up if the fraction is  .5. 2 3

9 Math Class Note the static modifier at the left of all the Math methods. All the methods in the Math class are static methods (also called class methods), which means they are called by prefacing the method's name with the name of the class in which they are defined. For example: int position1 = 15, position2 = 18; int distanceApart = Math.abs(position1 - position2); Write a Java statement that updates x's value so x gets the absolute value of its original value. Call Math methods by prefacing them with Math dot. 1. Would this work? Math.abs(x); No! The absolute value of x is found, but x is not updated! Solution: x = Math.abs(x); 1

10 Math Class Note that it's legal to pass an integer value to a method that accepts a floating-point argument. Note the following example. Horton’s Law says that the length of a river is related to the area drained by the river in accordance with this formula: length ≈ 1.4 (area)0.6 Here's how to implement Horton's Law in Java code: int area = 10000; // square miles drained double riverLength = 1.4 * Math.pow(area, 0.6); A common use of computers is to model real-world events that rely on random events. That's because computers are good at generating random numbers and being able to repeat the random events many, many times. 1 OK to pass an int (area), into pow, which accepts double arguments. 1. Note: Passing an integer value into a method that accepts a floating-point argument is like assigning an integer value into a floating-point variable, discussed in Chapter 3. 2. For example, you can use computers to optimize traffic-light signal patterns by simulating random car traffic. The computer would randomly generate car traffic over the course of a simulated week. Then, depending on how good the traffic flow was, the traffic light designer would tweak his/her traffic light signal patterns and run the simulation again. Later on, I'll show random being used within a complete program, but we first need to cover a few more Math class details… 2

11 Math Class The Math class contains a named constant, PI:
Pi, written as  in math books, is the ratio of a circle's perimeter to its diameter. It contains this double value: It's a constant, which means its value is fixed. If you attempt to assign a value to it, you'll get a compilation error. Just like Math's methods are class methods and they are accessed using the Math class name, Math's PI is a class variable and it is accessed using the Math class name. In other words, if you need pi, specify Math.PI. Complete this code fragment: double radius = 3.0; double volumeOfSphere = 1 [1. The book contains Math's other named constant, E.] 2. I coax the students to write this: 4 / 3 * Math.PI * radius * radius * radius; But 4 / 3 performs integer division and evaluates to 1, not 1.33 repeating. I erase 4 / 3 and replace it with this: 4.0 / 3.0 Note that we could have used Math.pow to calculate the cube of radius, but for easy powers like this, use the multiplication operator because that's more efficient than calling the pow method. 3. Why is PI in all uppercase? Proper style suggests using all uppercase for named constants. And Sun uses proper style in implementing the PI named constant. 2 3

12 Wrapper Classes For Primitive Types
A wrapper class is a class that surrounds a relatively simple item in order to add functionality to the simple item. Here are wrapper classes for some of the Java primitive types: Wrapper Class Primitive Type Integer int Long long Float float Double double Character char Note that the wrapper class names are the same as the primitive names except for the uppercase first letter. What are the exceptions to that rule? The wrapper classes are defined in the java.lang package. The Java compiler automatically imports all the classes in the java.lang package, so there's no need to import the wrapper classes explicitly. 1 1. A wrapper is actually a generic term for software that covers up (wraps up) something else, but we'll only use the term "wrapper" when describing the standard wrapper classes for the primitive types. 2. int's wrapper class = Integer. char's wrapper class = Character. 2

13 Wrapper Classes For Primitive Types
Most real-world Java programs use GUI I/O instead of text-based I/O. (GUI = graphical user interface. I/O = input/output.) What is text-based I/O? What is GUI I/O? With GUI programs, all numeric output is string based. So to display a number, you need to convert the number to a string prior to calling the GUI display method. All numeric input is string based, too. So to read a number in a GUI program, you first read the input as a string and then convert the string to a number. Here are string conversion methods provided by the numeric wrapper classes: Wrapper Class string  number number  string Integer Integer.parseInt(<string>) Integer.toString(<#>) Long Long.parseLong(<string>) Long.toString(<#>) Float Float.parseFloat(<string>) Float.toString(<#>) Double Double.parseDouble(<string>) Double.toString(<#>) 1 2 1. Text-based I/O is when all of your input and output appears as text in a simple black and white “console window.” We've been using text-based I/O for all of our programs so far because it's easier than GUI-based I/O. 2. GUI input is when you have a window with buttons, check boxes, text boxes, etc. The user uses his/her mouse to click buttons and check boxes and to select text boxes, etc. GUI-based I/O is covered in Chapters 16 and 17. 3. For Integer.parseInt, you pass in a string argument and the corresponding int is returned. For Integer.toString, you pass in an int argument and the corresponding string is returned. 4. Note how all the method calls are prefaced with the method's class name. That's because all the wrapper methods are class methods (just like Math methods are class methods). 3 4

14 Wrapper Classes For Primitive Types
1 Conversion examples - strings to numbers: String yearStr = "2002"; String scoreStr = "78.5"; int year = Integer.parseInt(yearStr); double score = Double.parseDouble(scoreStr); Remember - to convert a string to a numeric type, use X.parseX where X is the numeric type you're interested in. Conversion examples - numbers to strings : int year = 2002; double score = 78.5; String yearStr = Integer.toString(year); String scoreStr = Double.toString(score); 2 1. Here are some trivial examples that use the wrapper conversion methods. I'll show a non-trivial example shortly. 2. How would you convert a string to a long? Long.parseLong How would you convert a string to a float? Float.parseFloat [3. Alternative primitive to string technique: "" + number] 3

15 Wrapper Classes For Primitive Types
To find the largest and smallest possible values for a particular type, use the type's wrapper class and access the wrapper class's MAX_VALUE and MIN_VALUE named constants. For example: Integer.MAX_VALUE Double.MAX_VALUE Float.MIN_VALUE Write a lottery program that prompts the user to guess a randomly generated number between 0 and the maximum int value. The user pays $1.00 for each guess and wins $1,000,000 if the guess is correct. The user enters a "q" to quit. 1. I load Lottery.java and demo it. 2. Let's examine the code on the next slide … 1 2

16 Lottery Example import java.util.Scanner; public class Lottery {
public static void main(String[] args) Scanner stdIn = new Scanner(System.in); String input; int winningNumber = System.out.println("Want to win a million dollars?"); System.out.println("If so, guess the winning number (a" + " number between 0 and " + (Integer.MAX_VALUE - 1) + ")."); do System.out.print( "Insert $1.00 and enter your number or 'q' to quit: "); input = stdIn.nextLine(); Initialize winningNumber to a randomly chosen integer between 0 and the largest possible int. 1 2 1. I read the green box and lead the students to the solution by drawing a number line with a mark between 0 and 1 (not touching 1). I show how if you multiply a number that's between 0 and 1 by MAX_VALUE, you'll get a number between 0 and MAX_VALUE. I coax the students to write this: int winningNumber = (int) (Math.random() * Integer.MAX_VALUE); 2. I walk through the code, but skip the "give me a hint" if statement for now.

17 Lottery Example if (input.equals("give me a hint")) // a back door {
1 if (input.equals("give me a hint")) // a back door { System.out.println("try: " + winningNumber); } else if (!input.equals("q")) if ( System.out.println("YOU WIN!"); input = "q"; // force winners to quit else System.out.println( "Sorry, good guess, but not quite right."); } // end else if } while (!input.equals("q")); System.out.println("Thanks for playing. Come again!"); } // end main } // end Lottery class Compare input with the winning number. 2 1. I walk through the code, read the green box, assume the proper code is inserted there, and continue walking through the rest of the class. 2. I coax the students to write this: if (Integer.parseInt(input) == winningNumber) 3. What is the purpose behind the "back door"? For testing purposes, it allows the user to see the randomly-generated number, so the user can enter it. 4. A back door is a computer term for a secret mechanism in a program that allows someone to do something special. I demo Lottery.java's back door by entering "give me a hint". 3 4

18 Character Class 1 To perform character-related operations, use the Character wrapper class. Here are some of the more popular methods in the Character class. Each method receives a single char parameter. Method Name Description Return Type Example Return Value isDigit check if given character is a digit boolean Character.isDigit('8') Character.isDigit('t') Character.isDigit('&') true false isLetter check if given character is a letter Character.isLetter('B') Character.isLetter('-') isUpperCase check if given character is an uppercase letter Character.isUpperCase('C') Character.isUpperCase('c') Character.isUpperCase('$') isLowerCase check if given character is a lowercase letter Character.isLowerCase('b') Character.isLowerCase('B') 2 3 [1. The character class is needed if the variable name checker project is assigned, but otherwise, the Character class can be skipped during lecture.] 2. Oftentimes, you'll need to write programs that manipulate individual characters in a string of text. For example, you might need to read in a social security number and store just the nine digits, skipping the dashes if there are any. To check for digits, use the isDigit method…. 3. I read the examples for each of the methods. 4. Are these methods static? Yes, and you can tell because the methods are called using the class name dot syntax, which is how you call static members. 4

19 Character Class Method Name Description Return Type Example
Return Value isLetterOrDigit check if given character is a letter or digit boolean Character.isLetterOrDigit('b') Character.isLetterOrDigit('6') Character.isLetterOrDigit(';') true false isWhitespace check if given character is whitespace (blank, tab, newline) Character.isWhiteSpace(' ') Character.isWhiteSpace('\n') Character.isWhiteSpace('i') toUpperCase return uppercase version of given character char Character.toUpperCase('e') Character.toUpperCase('E') Character.toUpperCase('4') 'E' '4' toLowerCase return lowercase version of given character Character.toLowerCase('G') Character.toLowerCase('g') Character.toLowerCase('*') 'g' '*' 1 2 1. I read the examples for each of the methods. 2. Note: whitespace = blank, tab, or newline 3. If the given character is a lowercase letter, toUpperCase returns the uppercase version of it. Otherwise, it returns the given character itself. 3

20 Character Class Write a Java statement that updates ch's value so ch gets the uppercase version of its original value. 1 1. Would this work? Character.toUpperCase(ch); No! The uppercase value of ch is found, but ch is not updated! Solution: ch = Character.toUpperCase(ch);

21 Character Class This program checks a user entry to see if it's a legal identifier. import java.util.Scanner; public class IdentifierChecker { public static void main(String[] args) Scanner stdIn = new Scanner(System.in); String line; // user entry char ch; boolean legal = true; // Is entered line a legal identifier? System.out.println("This program checks the validity" + " of a proposed Java identifier."); System.out.print("Enter a proposed identifier: "); line = stdIn.nextLine(); ch = line.charAt(0); if (!(Character.isLetter(ch) || ch == '$' || ch == '_')) legal = false; } 1 2 3 4 1. What's an identifier? A class name, method name, or variable name. 2. Remember the rules for forming a legal Java identifier? Must consist entirely of letters, digits, dollar signs ($), and/or underscore (_) characters. The first character must not be a digit. If these rules are broken, your program won't compile. 3. I load IdentifierChecker.java and demo it. 4. I walk through the program.

22 Character Class for (int i=1; i<line.length() && legal; i++) {
ch = line.charAt(i); if (!(Character.isLetterOrDigit(ch) || ch == '$' || ch == '_')) legal = false; } if (legal) System.out.println( "Congratulations, " + line + " is a legal Java identifier."); else "Sorry, " + line + " is not a legal Java identifier."); } // end main } // end class IdentifierChecker

23 The String Class In Chapter 3, you saw several String methods - charAt, length, equals, and equalsIgnoreCase. Those methods are defined in the String class, along with quite a few other methods that help with string manipulation tasks. The String class is defined in the java.lang package. The Java compiler automatically imports all the classes in the java.lang package, so there's no need to import the String class explicitly. We'll now present several of the more popular methods in the String class.

24 The String Class's substring Method
Here are API headers and brief descriptions for two alternative forms of the substring method: public String substring(int beginIndex) Returns a string that is a subset of the calling-object string, starting at the beginIndex position and extending to the end of the calling-object string. public String substring(int beginIndex, int afterEndIndex) Returns a string that is a subset of the calling-object string, starting at the beginIndex position and extending to the afterEndIndex-1 position. 1 2 1. The calling-object string is the string that appears at the left of the method call; it's the string that calls the method. Go to the next slide, note the calling object, read the first bullet item, and return here. 2. Note that there's no static modifier in the substring headers. The static modifier appears in all the Math methods because those methods are class methods. You call class methods by prefacing the method call with the class name (e.g., Math.abs(-2)) String methods are not class methods, so you don't preface string method calls with the class name, String. Instead, you preface string method calls with the particular string that you're interested in. 3. Study the second substring call on the next slide. 3

25 The String Class's substring Method
public class StringMethodDemo { public static void main(String[] args) String candide = "we must cultivate our garden"; System.out.println(candide.substring(8)); System.out.println(candide.substring(3,17)); } // end main } // end StringMethodDemo calling object 1 2 1. This program processes a quote from Candide. As you may recall, string indices start at 0. So in candide.substring(8), the 8 refers to candide's ninth character, which is 'c'. Thus, the program prints "cultivate our garden." 2. What does the second print statement print? In candide.substring(3,17), the 3 and 17 refer to the fourth and eighteenth characters, 'm' and a space. Thus, the program prints "must cultivate."

26 The String Class's indexOf Method
Here are API headers and brief descriptions for four alternative forms of the indexOf method: public int indexOf(int ch) Returns the position of the first occurrence of the given ch character within the calling-object string. Returns -1 if ch is not found. public int indexOf(int ch, int fromIndex) Returns the position of the first occurrence of the given ch character within the calling-object string, starting the search at the fromIndex position. Returns -1 if ch is not found. public int indexOf(String str) Returns the position of the first occurrence of the given str string within the calling-object string. Returns -1 if str is not found. public int indexOf(String str, int fromIndex) Returns the position of the first occurrence of the given str string within the calling-object string, starting the search at the fromIndex position. Returns -1 if str is not found. 1 1. Read the entire next slide, and return here.

27 The String Class's indexOf Method
public class StringMethodDemo { public static void main(String[] args) String hamlet = "To be or not to be: That is the question."; int index = hamlet.indexOf(':'); String hamlet2 = hamlet.substring(index + 2); System.out.println(hamlet2); } // end main } // end StringMethodDemo 1. What does the program print? That is the question. 1

28 The String Class's lastIndexOf Method
The lastIndexOf methods are identical to the indexOf methods except that they search the calling-object string from right to left. For the one-parameter lastIndexOf method, the search starts from the rightmost character. For the two-parameter lastIndexOf method, the search starts from the position specified by the second parameter. What does this code fragment print? String einsteinQuote = "Peace cannot be kept by force; it can" + " only be achieved by understanding." System.out.print( einsteinQuote.indexOf("can") + " " + einsteinQuote.indexOf("can", 7) + " " + einsteinQuote.lastIndexOf("can")); 1. Hint: the semicolon is at position 29. 1

29 Formatted Output with the printf Method
1 You should strive to make program output be understandable and attractive. To further that goal, format your output. Here's an example of formatted output: Account Actual Budget Remaining Office Supplies , , Photocopying , , (100.11) Total remaining: $149.89 The System.out.printf method is in charge of generating formatted output. 2 1. Up to this point, we've written programs without worrying too much about the format of a program's output. You need the format to be good so that people can understand the output. 2. What formatting do you see in the budget report? The left column is left-aligned. The other columns are right aligned. The numbers show two digits at the right of the decimal point. The numbers show commas between every third digit at the left of the decimal point. The numbers show parentheses to indicate negativeness. 3. The printf method has lots of formatting features. We'll keep things simple and explain only a few of the more popular features. We'll begin our explanation of the printf method by showing you how to generate the "Total remaining" line in the above budget report. Next slide…. 3

30 Formatted Output with the printf Method
Here's how to generate the "Total remaining" line in the previous slide's budget report: System.out.printf( "\nTotal remaining: $%.2f\n", remaining1 + remaining2); You can have as many format specifiers as you like in a given format string. For each format specifier, you should have a corresponding data item/argument. format specifier 1 2 1. The printf method's first argument is known as the format string. It contains text that prints as is plus format specifiers that handle formatted printing. In the above example, "\nTotal remaining: $...\n" is the text that prints as is. And %.2f is the format specifier. Think of a format specifier as a hole where you plug in a data item. In the above example, remaining1 + remaining2 is the data item that gets plugged in. If remaining1 + remaining2 holds , then gets plugged into the format specifier hole. I go to the previous slide and show in the bottom line of output. 2. The format specifier starts with % because all format specifiers must start with %. The format specifier's .2 causes two digits to be displayed after the decimal point. The format specifier's f indicates that the data item is a floating-point number. [3. If you include fewer data items than specifiers, you get a runtime error. If you include more data items than specifiers, the right-most extra data items are ignored.] 3

31 Format Specifier Details
1 Here's the syntax for a format specifier: %[flags][width][.precision]conversion-character The square brackets indicate that something is optional. So the flags, width, and precision parts are optional. Only the % and the conversion character are required. 2 3 1. Format specifiers are very powerful. I won't bother to comprehensively cover all of their power, but I'll provide enough details to get you up and running. If you come across a formatting issue that you can't resolve with this limited coverage, look up printf on Sun's Java API Web site and search for format string details. 2. You've already seen the % thing. It indicates the start of a format specifier. The flags, width, precision, and conversion-character represent the different parts of a format specifier. Each of them specifies a different formatting trait. We'll cover the items in right-to-left order. Thus, we'll cover the conversion character first. 3. Let's talk about the conversion character in detail….

32 Conversion Character The conversion character tells the Java Virtual Machine (JVM) the type of thing that is to be printed. Here is a partial list of conversion characters: s This displays a string. d This displays a decimal integer (an int or a long). f This displays a floating-point number (a float or a double) with a decimal point and at least one digit to the left of the decimal point. e This displays a floating-point number (float or double) in scientific notation. 1 2 1. For example, it might tell the JVM to print a string or it might tell the JVM to print a floating-point number. 2. What's a decimal integer? Base 10! Java has base 16 integers also (hexadecimal), but we won't bother to discuss them because they're not used all that often. 3. We'll show an example on the next slide that uses these conversion characters…. 3

33 Conversion Character This code fragment illustrates how to use the conversion characters: System.out.printf("Planet: %s\n", "Neptune"); System.out.printf("Number of moons: %d\n", 13); System.out.printf("Orbital period (in earth years): %f\n", ); System.out.printf( "Average distance from the sun (in km): %e\n", ); Here is the output: Planet: Neptune Number of moons: 13 Orbital period (in earth years): Average distance from the sun (in km): e+09 1 1. I walk through the Sop statements and show the corresponding output. 2. Note that by default, the f and e conversion characters print six digits at the right of the decimal point. 2

34 Precision and Width Precision: Width:
1 Precision: Applies only to floating-point numbers (i.e., it works only in conjunction with the f and e conversion characters). Its syntax consists of a dot and then the number of digits that are to be printed to the right of the decimal point. If the data item has more fractional digits than the precision specifier's value, then rounding occurs. If the data item has fewer fractional digits than the precision specifier's value, then zeros are added at the right so the printed value has the specified number of fractional digits. Width: Specifies the minimum number of characters that are to be printed. If the data item contains more than the specified number of characters, then all of the characters are printed. If the data item contains fewer than the specified number of characters, then spaces are added. By default, output values are right aligned, so when spaces are added, they go on the left side. 1. It's now time to discuss the precision and width parts of a format specifier.

35 Precision and Width This code fragment illustrates how to specify precision and width in a format specifier: System.out.printf("Cows are %6s\n", "cool"); System.out.printf("But dogs %2s\n", "rule"); System.out.printf("PI = %7.4f\n", Math.PI); Here is the output: Cows are cool But dogs rule PI = 1 6 characters 1. I walk through the Sop statements and show the corresponding output. 2. In the third statement, note the %7.4f specifier. It's easy to get fooled by the 7.4. It looks like it might be saying "seven places to the left of the decimal point and four places to the right of the decimal point," but it's actually saying "seven total spaces, with four places to the right of the decimal point." And don't forget that the decimal point is counted as one of those seven total spaces. Math.PI's value is …, and when it gets printed with four places to the right of the decimal point, it gets rounded to 2 7 characters

36 Flags 1 Flags allow you to add supplemental formatting features, one flag character for each formatting feature. Here's a partial list of flag characters: - Display the printed value using left justification. 0 If a numeric data item contains fewer characters than the width specifier's value, then pad the printed value with leading zeros (i.e., display zeros at the left of the number). , Display a numeric data item with locale-specific grouping separators. In the United States, that means commas are inserted between every third digit at the left of the decimal point. ( Display a negative numeric data item using parentheses, rather than a minus sign. Using parentheses for negative numbers is a common practice in the field of accounting. 1. We've covered the conversion character, precision, and width parts of a format specifier. It's now time to discuss the flags part. 2. Let's see how format specifiers work in the context of a complete program…. 2

37 BudgetReport Example public class BudgetReport {
1 public class BudgetReport { public static void main(String[] args) final String HEADING_FMT_STR = "%-25s%13s%13s%15s\n"; final String DATA_FMT_STR = "%-25s%,13.2f%,13.2f%(,15.2f\n"; double actual1 = ; // amount spent on 1st account double budget1 = 1400; // budgeted for 1st account double actual2 = ; // amount spent on 2nd account double budget2 = 2000; // budgeted for 2nd account double remaining1, remaining2; // unspent amounts System.out.printf(HEADING_FMT_STR, "Account", "Actual", "Budget", "Remaining"); " ", "------", "------", " "); left justification parentheses for negatives, comma for group separators 3 1. This is the program that generated the budget report on the earlier slide. I go back to that slide and look at the output. 2. Note that we use the same format string for printing the column headers and the column underlines, and the format string is stored in a HEADING_FMT_STR named constant. If you use a format string in more than one place, it's a good idea to save the format string in a named constant and use the variable in the printf statements. Why? By storing the format string in one common place (in a named constant), you ensure consistency and you make it easier to update the format string in the future. 3. Note the minus sign in the HEADING_FMT_STR and DATA_FMT_STR format strings. That left justifies the first column's data. Note the commas in the DATA_FMT_STR format string. That causes locale-specific characters (commas in the United States) to appear between every third digit at the left of the decimal point. Note the left parenthesis in the DATA_FMT_STR format string. That causes negative numbers to use parentheses instead of a minus sign. 2

38 BudgetReport Example remaining1 = budget1 - actual1 ;
System.out.printf(DATA_FMT_STR, "Office Supplies", actual1, budget1, remaining1); remaining2 = budget2 - actual2; "Photocopying", actual2, budget2, remaining2); System.out.printf( "\nTotal remaining: $%(,.2f\n", remaining1 + remaining2); } // end main } // end class BudgetReport 1. I walk through the code and show how the data lines are printed. I refer back to the output from the earlier slide, if necessary.

39 Chapter 5 - Quiz Questions
What is the name of the class that contains the abs, min, and round methods? Arithmetic Math Number The Integer and Character classes are examples of framework classes hover classes wrapper classes 1. b 2. c


Download ppt "Chapter 5 - Using Pre-Built Methods"

Similar presentations


Ads by Google