190 likes | 319 Views
Formatted Output Random numbers. Chapter 6: Odds and Ends. Recall the Carpet Pricing Example. The price table for carpets ranging in size from 11 x 5 to 20 x 25 ft. whose unit price is $15 per sq. ft.
E N D
Formatted Output Random numbers Chapter 6: Odds and Ends
Recall the Carpet Pricing Example The price table for carpets ranging in size from 11 x 5 to 20 x 25 ft. whose unit price is $15 per sq. ft. The outer for statement ranges from the first row (width = 11) to the last row (width = 20). For each repetition of the outer for, the inner for statement is executed, which ranges from the first column (length = 5) to the fifth (length = 25).
Output is a Table But the numbers don't line up properly 5 10 15 20 25 11 825 1650 2475 3300 4125 12 900 1800 2700 3600 4500 13 975 1950 2925 3900 4875 14 1050 2100 3150 4200 5250 15 1125 2250 3375 4500 5625 16 1200 2400 3600 4800 6000 17 1275 2550 3825 5100 6375 18 1350 2700 4050 5400 6750 19 1425 2850 4275 5700 7125 20 1500 3000 4500 6000 7500
Formatting Output To align values with varying numbers of digits, we must vary the number of spaces in front of the values. The idea behind formatted output is to allocate the same amount of space for the output values and align the values within the allocated space. We call the space occupied by an output value thefield. The number of characters allocated to a field is the field width.
Aligning Columns of Numbers How to place a varying number of spaces to align the output values. Hyphen is used here to indicate the blank space. One approach to determine how many spaces each number takes up and then pad with spaces to make it the the desired width. Better to use the Formatter class from Java 1.5.
Formatter class A Formatter is created with a PrintStream. Formatter fmt = new Formatter( System.out); The format method is used with a format string that tells how to position the output values. fmt.format( "%8d", price); The format string is kind of like the 'picture' we used for DecimalFormat and DateFormat objects. Formatter is in the java.util package.
The format method The format method is what we call a variatic method It can take a variable number of arguments (one or more) There must be a format string The format string must contain a picture for each of the other arguments The format string can contain text that will also show up in the output
Format Codes % starts the picture for a value The number after the % is the field width The letter at the end is the type of the output value d => int s => String f => double in this case the number looks like x.y where the x is the total field width and the y is the number of digits after the decimal point
Some Examples Formatter formatter = new Formatter( System.out); int num1 = 34, num2 = 9, num3; num3 = num1 + num2; formatter.format( "%3d + %3d = %5d\n", num1, num2, num3); String name = "John"; formatter.format( "Hello, %s!\n", name); GregorianCalendar day = new GregorianCalendar( 1776, 6, 4) formatter.format( "%1$tB %1$te, %1$tY\n", day);
Other format methods The signature is the same as the one in the Formatter class PrintStream has a format method System.out.format( formatString, varList); String has a static format method that returns a String String result = String.format( formatString, varList);
Example: Loan Tables The goal of this exercise is to design a program that generates a loan table. The table will compare different monthly payments for a set loan amount, with varying loan periods in each column and different interest rates in each row.
Loan Tables The start method can be expressed as tell the user what the program does; prompt the user "Do you want to generate a loan table?"; while (the user says YES) input the loan amount; generate the loan table; prompt the user "Do another loan table?";
Pseudocode The start method was expressed in pseudocode. Pseudocode is an informal language used to express an algorithm. It is useful in clarifying the purpose or function of the program without being tied down to the syntactic rules of a particular programming language. Also useful for describing algorithms that may be implemented in many different languages.
Loan Tables Other methods in the program: describeProgram: tells the user what the program does if the user requests it. getLoanAmount: gets the loan amount from the user. generateLoanTable: generates the loan table. To compute the monthly loan payment, reuse the Loan class defined in Chapter 4.
Random Number Generation The method Math.random is called a pseudorandom number generator and returns a number of type double that is greater than or equal to 0.0 but less than 1.0. The generated number is called a pseudorandom number because it is not truly random.
Random Integers The number returned from the random method ranges from 0.0 up to (but not including) 1.0. If we want to generate random integers, we must perform a conversion so the number will fall within the desired range. Use the formula: Y = {X * (max – min + 1)} + min where X is the number returned by random.
Random Integers The formula expressed in Java: //assume correct values are assigned to //'max' and 'min' int randomNumber = (int) (Math.floor(Math.random() * (max-min+1)) + min);
Random Number Example Ch6TestRandomGenerator generates N random numbers between 1 and 4 to simulate the suit of a drawn card. It keeps one counter for each suit, and increments the matching counter after a random number is generated. At the end of the generation, it prints the ratio count/N.
Random Class The Random class is part of the java.util package It provides methods that generate pseudorandom numbers of various types float nextFloat() int nextInt() int nextInt(n) produces integer in range 0 to n-1