Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 20 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
20
Dung lượng
485,84 KB
Nội dung
58 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r FIGURE 3.2 The NumberMaker displays random numbers generated by the Math.random() method. The java.util.Random Class Another way that you can generate random numbers is by using the Random class in the java.util package. The Random class offers different methods for different data types. Specifically, it can generate random booleans, doubles, floats, ints, and longs. Refer to Table 3.1 for a list of these methods. Method Description boolean nextBoolean() Randomly returns either true or false boolean values. double nextDouble() Returns a random double value ranging from 0.0 (inclusive) to 1.0 (exclusive). float nextFloat() Returns a random float value ranging from 0.0 (inclusive) to 1.0 (exclusive). int nextInt() Returns a random int value (all 232 values are possible). int nextInt(int n) Returns a random int value ranging from 0 (inclusive) to n (exclusive). long nextLong() Returns a random long value (all 264 values are possible). TABLE 3.1 SOME JAVA . UTIL .R ANDOM M ETHODS In order to call one of the methods in Table 3.1, you need to create a new Random object first, and then use that object to call the desired method. The Number- MakerUtil application demonstrates how this is done. Take a look at the source code: /* * NumberMakerUtil * Uses java.util.Random to generate random numbers */ JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 58 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. import java.util.Random; public class NumberMakerUtil { public static void main(String args[]) { Random rand = new Random(); System.out.println(“Random Integers:”); System.out.println(rand.nextInt() + “, “ + rand.nextInt() + “, “ + rand.nextInt()); int iLimit = 11; System.out.println(“\nRandom Integers between 0 and 10:”); System.out.println(rand.nextInt(iLimit) + “, “ + rand.nextInt(iLimit) + “, “ + rand.nextInt(iLimit)); System.out.println(“\nRandom Floats:”); System.out.println(rand.nextFloat() + “, “ + rand.nextFloat() + “, “ + rand.nextFloat()); System.out.println(“\nRandom Booleans:”); System.out.println(rand.nextBoolean() + “, “ + rand.nextBoolean() + “, “ + rand.nextBoolean()); } } The output of the NumberMakerUtil program is displayed in Figure 3.3. 59 C h a p t e r 3 T h e F o r t u n e T e l l e r : R a n d o m N u m b e r s, C o n d i t i o n a l s, a n d A r r a y s FIGURE 3.3 This is the output of the NumberMakerUtil program. It generates random numbers and boolean values by using the java.util. Random class. In the source code, you do the following things. First, you create a Random object: Random rand = new Random(); JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 59 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. This makes rand an instance of the Random class and you use it to generate ran- dom values. Now that you have created rand, you can call the methods defined in the Random class. In this code: int iLimit = 11; System.out.println(“\nRandom Integers between 0 and 10:”); System.out.println(rand.nextInt(iLimit) + “, “ + rand.nextInt(iLimit) + “, “ + rand.nextInt(iLimit)); You declare iLimit to be an int whose value is 11. Then you make calls to the nextInt(int n) method to generate random numbers from 0 to 10. The range is from 0 to 10, as you remember, because 11 is the upper limit and is not a possi- ble value. In this program, you also use some other methods shown in Table 3.2. When you call the Math.random() method, you get the same result as if you cre- ated a Random object and made a call to the Random.nextDouble() method. In fact, when you call the Math.random() method, it creates a Random object and calls its nextDouble() method. That Random object is used thereafter in subse- quent calls to Math.random(). The Random class actually generates pseudorandom numbers. pseudorandom numbers are generated in a completely nonrandom way, but in a way that simu- lates randomness. The way Random methods do this is by taking a seed, an initial value (basically), and via some specific algorithm, generates other values based on the seed. An algorithm is a finite number of problem-solving steps (a solution to a specific problem or a way to get from point A to point B). Every Random object has a seed that it feeds through its randomization algorithm. This method can create all possible values with equal frequency given any seed. The values occur in order, but given infinite number of passes through the algorithm, all values are possible. If you don’t specify Random’s seed (you can, by the way), it is initialized by the value of the system clock in milliseconds. The system clock is your computer’s interpretation of the current time. Because the algorithm is not random, you’d come to the conclusion that one specific seed will generate a non-randomly ordered list of numbers. You’d be right and now you know why Random’s methods start with “ next ”. Furthermore, you would be willing to bet your paycheck that if two Random objects use the same seed, they both generate the same list of pseudorandom numbers. You would double your money because that’s exactly the case. Take a look at the AmIRandom program, which demonstrates the concept of the seed and pseudorandom numbers. /* * AmIRandom * Demonstrates the concept of a seed and pseudorandom numbers */ HINT 60 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 60 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. import java.util.Random; public class AmIRandom { public static void main(String args[]) { //don’t specify a seed Random rand1 = new Random(); //the number in parentheses is the seed Random rand2 = new Random(12345); //Or you can do it this way by using setSeed Random rand3 = new Random(); rand3.setSeed(12345); System.out.println(“\nrand1’s random numbers:”); System.out.println(rand1.nextInt() + “ “ + rand1.nextInt() + “ “ + rand1.nextInt()); System.out.println(“\nrand2’s random numbers:”); System.out.println(rand2.nextInt() + “ “ + rand2.nextInt() + “ “ + rand2.nextInt()); System.out.println(“\nrand3’s random numbers:”); System.out.println(rand3.nextInt() + “ “ + rand3.nextInt() + “ “ + rand3.nextInt()); } } There are three Random objects, rand1, rand2, and rand3. You don’t specify rand1’s seed, so the system clock is checked. But, you did set the seed for rand2 and rand3 to 12345. You set rand1’s seed by putting that number in as a parame- ter when creating the Random object. Random rand2 = new Random(12345); You set rand3’s seed after it was already assigned its Random object by using the setSeed() method: rand3.setSeed(12345); As you can see in Figure 3.4, rand1’s random numbers vary each time you run the program, but rand2’s and rand3’s numbers are invariably 1553932502, –2090749135, and –287790814. Now that you know two ways to generate randomization, you might be wonder- ing which one you should use. Some programmers opt to use Math.random() for its simplicity. When you use that method, you don’t have to explicitly create a 61 C h a p t e r 3 T h e F o r t u n e T e l l e r : R a n d o m N u m b e r s, C o n d i t i o n a l s, a n d A r r a y s JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 61 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. The Math Class You used the Math.random() method to generate random numbers. Now you learn more about the Math class. The Math class defines methods for performing basic mathematical operations such as calculating absolute values, exponents, logarithms, square roots, and trigonometric functions. Table 3.2 lists some of these methods. Note that not all versions of a particular method are listed. For example, there are versions of Math.abs() that accept data types: int, long, float, and double. Refer to the Math class in the Java documentation for more detailed information. The MathClassTest application shows how to use some of these methods and by comparing the source code to the output, as shown in Figure 3.5, you’ll get a bet- ter idea of what these methods do: Random object yourself. On the other hand, I find it easier to use the Random class in programs that need a specific type and range of random data. You can use Math.random() to generate ranges of random integers, longs, or whatever, but you have to parse the double values and perform mathematical operations. 62 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r FIGURE 3.4 This is the output of the AmIRandom application. rand2 and rand3 will always generate the same output. INTHEREAL WORLD In the real world, one use for random numbers is to create the element of sur- prise in video games. Games such as Tetris, Solitaire, and Minesweeper would- n’t be any fun if every time you played it, the same thing happened. Eventually, you’d memorize it all and it wouldn’t be a game anymore, it would be monoto- nous. You would always know where the mines are, or where the aces are, or what the next hundred or so Tetris blocks would be. You’d have to put the games aside and actually get some work done. How boring! JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 62 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 63 C h a p t e r 3 T h e F o r t u n e T e l l e r : R a n d o m N u m b e r s, C o n d i t i o n a l s, a n d A r r a y s Math Method Description Math.abs(int n) Absolute value (n or 0-n, whichever is greater) Math.acos(double d) Arc cosine of d Math.asin(double d) Arc sine of d Math.atan(double d) Arc tangent of d Math.ceil(double d) Ceiling (smallest value not less than d that is an integer) Math.cos(double d) Cosine of d Math.exp(double d) (ed, where e=2.718 ) Math.floor(double d) Floor (highest value not greater than d that is an integer) Math.log(double d) Natural logarithm of d Math.pow(double a, double b) a b Math.random() Generates a random number between 0.0 and 1.0 Math.round(float f) Rounds f to the nearest int value Math.round(double d) Rounds d to the nearest long value Math.sin(double d) Sine of d Math.sqrt(double d) Square root of d Math.tan(double d) Tangent of d Math.toDegrees(double d) Converts d (in radians) to degrees Math.toRadians(double d) Converts d (in degrees) to radians TABLE 3.2 M ATH C LASS METHODS FIGURE 3.5 The MathClassTest application output. JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 63 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 64 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r INTHEREAL WORLD In the real world, you will write your code in such a way that it acts differently based on what the value of a random number is. Using the Tetris game exam- ple again, there are only seven differently shaped blocks that can possibly fall into the play area. In this instance, you only need to handle seven possibilities, so you only need a random number that only can be one of seven values, such as 0 through 6. /* * MathClassTest * Demonstrates use of Math class methods */ public class MathClassTest { public static void main(String args[]) { double d = -123.456; System.out.println(“My number is: “ + d); System.out.println(“The absolute value is: “ + Math.abs(d)); System.out.println(“The ceiling is: “ + Math.ceil(d)); System.out.println(“The floor is: “ + Math.floor(d)); System.out.println(“Rounded off, it is: “ + Math.round(d)); System.out.println(“The square root of 100 is “ + Math.sqrt(100)); System.out.println(“3^2 is: “ + Math.pow(3, 2)); } } Controlling the Random Number Range You know how to use Math.random() to generate random double values ranging from 0.0 to 1.0. You also know how to use the java.util.Random class to gener- ate random numbers. You can use it to generate all possible int and long values, as well as floats and doubles ranging from 0.0 to 1.0. You also know how to have limited control of random int values using the Random.nextInt(int n) method, which gives you a range from 0 to (n-1). This section covers how to generate ran- dom numbers that fit within a specific range. JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 64 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Getting Values Larger Than 1 When you use Math.random(), the largest value you can get is less than 1.0. To get values larger than 1, you multiply the value returned by Math.random() by the number you want to have as the upper limit of random numbers. For example: double d = Math.random() * 45.0; In this line of code, d is assigned a random value ranging from 0.0 (inclusive) to 45.0 (exclusive). You can do the same thing when using Random methods with ran- dom floating point numbers. Okay, so now you can get a range of numbers, but the lower limit has to be 0.0. Specifying a Range If you needed to get a more specific range, say from 32.0 to 212.0, you could do it this way: double d = Math.random() * 180 + 32; The d variable is assigned a random value from 32.0 (inclusive) to 212.0 (exclu- sive). Here’s how it works. As you know, Math.random() returns some random value between 0.0 and 1.0. This value is multiplied by 180 because 212.0 – 32.0 = 180.0 . The difference between the lower and upper limit ranges from 0.0 to 180.0. When 32 is added to that value, the range becomes 32.0 to 212.0, just like you needed. If you need a range of integers; for example, from 1 to 10 inclusive, you do it this way: int n = (int) (Math.random() * 10 + 1); This code assigns a random int ranging from 1 to 10 inclusive. Math.random() generates a random number from 0.0 to 1.0; the range is multiplied by 10 and becomes 0.0 to 10.0. Add 1 to that and now it ranges from 1.0 to 11.0. Remem- ber that the upper limit is not a possible value. The lowest possible value is 1.0 and the highest possible value is essentially 10.99999 When you cast this posi- tive value to an int, it has the same effect as using Math.floor() because it is truncated (the fractional portion is ignored). The Dice Roller Want to write a program using random numbers that actually does something meaningful? The DiceRoller application simulates rolling dice. When you run it, it displays two dice with randomly generated face values. Here is a source listing of DiceRoller.java: 65 C h a p t e r 3 T h e F o r t u n e T e l l e r : R a n d o m N u m b e r s, C o n d i t i o n a l s, a n d A r r a y s JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 65 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. /* * DiceRoller * Simulates rolling of die using random * values between 1 and 6 (inclusive). * Two methods of random number generation are used. */ import java.util.Random; public class DiceRoller { public static void main(String args[]) { double rand; Random random = new Random(); int die1; int die2; System.out.println(“Rolling dice ”); // Get random double using Math.random() rand = Math.random(); // get a value between 0.0 (inclusive) and 6 (exclusive) rand = rand * 6; // cast it to an integer and add 1 // to get an int between 1 and 6 (inclusive) die1 = (int) (rand + 1); // Get random int between 0 and 5 (inclusive) and add 1 // using java.util.Random die2 = random.nextInt(6) + 1; System.out.println(“You rolled: [“ + die1 + “][“ + die2 + “]”); } } The rand variable is a double value that holds the random value returned by Math.random(). random is a Random object, and die1 and die2 are integers that rep- resent the face value of a set of dice. You take the two approaches to generating random numbers that you’ve learned to produce this effect. Figure 3.6 shows the output. When this program generates the value for die1, it calls the Math.random() method. It uses the algorithm described in the previous section for generating the specific range of 1 to 6. The program uses three separate lines to generate the random number to make the steps in the process clear, but it can all be done with one statement like this: die1 = (int) (Math.random() * 6 + 1); 66 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 66 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. The program demonstrates how to generate this range using the java.util. Random class. The die2 variable gets its value this way. The call to the Random. nextInt(int n) method returns a random integer between 0 and 5 inclusive, so you just need to add 1 to shift that range to where you need it to be. The if Statement Wouldn’t it be great if you could conditionally direct the flow of your program based on certain conditions? You can do this by using conditional statements. Conditional statements test for certain conditions and execute or skip statements based on the results. For example, you can generate a random number and have the program print “Even” only when the random number is even: if (myRandomNumber % 2 == 0){ System.out.println(“Even”); } The expression within the parentheses is the condition. If the condition is true, the System.out.println(“Even”) statement is executed. This particular if state- ment prints “Even” only when myRandomNumber is even. Recall that % is the mod- ulus operator, so any number that is evenly divided by two (the remainder is 0) is even. The equality operator == results in the boolean value of true or false. When used with numbers or expressions that evaluate to numbers, the value will be true only when the number on the left side is equal to the number on the right side. The syntax for the if statement is as follows: if (condition) { java statements; } The if keyword is followed by a condition within parentheses. The statements that execute if the condition is true are placed within the braces. Recall that a 67 C h a p t e r 3 T h e F o r t u n e T e l l e r : R a n d o m N u m b e r s, C o n d i t i o n a l s, a n d A r r a y s FIGURE 3.6 The DiceRoller application is a simulation of rolling dice. JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 67 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... allows for execution of a conditional choice of two statements, executing one or the other but not both The syntax is as follows: if (condition) { java_ statements _for_ true_condition; } else { java_ statements _for_ false_condition; } If the condition is true, the program executes the statements represented here by java_ statements _for_ true_condition If the condition is false, the statements represented by java_ statements _for_ false_condition... - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 75 75 … Java Statements … if Condition true false FIGURE 3.9 else The flowchart shows that a Java program executes one of two sets of statements depending on the value of the condition … Java Statements … … Java Statements … … Java Statements... object That is, technically speaking, they must both TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark The Fortune Teller: Random Numbers, Conditionals, and Arrays Syntax Chapter 3 Operator JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 70 Java Programming for the Absolute Beginner 70 point to (reference) the same memory location...JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 68 Java Programming for the Absolute Beginner 68 group of statements within a set of braces is collectively called a block statement The braces are optional if you need to execute only one statement Figure 3.7 shows the flow of a conditional statement You can see that if the condition is true, the flow of the program is directed toward executing some Java. .. variables For example: Chapter 3 about it because str.charAt(1) isn’t evaluated by the JRE at all if str.length() is not greater than 1 This works similarly with the conditional-OR operator except if the left side is true, the right side is ignored and the result is true The right side is evaluated only when the left side is false JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 72 72 Java Programming for the Absolute. .. service has not been initialized and will cause a run-time error JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 76 Java Programming for the Absolute Beginner 76 the else structure, you must place the else keyword directly after the corresponding if statement If you do not, you get a compiler error to the effect “else without if” and you are forced to fix your code to get it to compile correctly Getting back... conditional expressions to test for certain states of the operands There are conditional operators used for comparison, for testing equality, and there are also conditional-AND and conditional-OR operators that are used to form compound conditions by grouping conditions together The four numerical comparison operators (=), also called relational operators, are used for comparing numerical data... statement or statements These statements are not executed if the condition is false … Java Statements … FIGURE 3.7 This flow chart shows how conditions affect the flow of the program If the condition is true, some Java statements execute that would not execute otherwise if Condition true false … Java Statements … … Java Statements … Conditions and Conditional Operators Conditions evaluate to either... source code for LowTemp .java: /* * LowTemp * Uses the if statement to display a message * that depends on whether or not the random * temperature is low Also demonstrates how * to get a random number within a specific range */ import java. util.Random; public class LowTemp { public static void main(String args[]) { int min = -40; int max = 120; int diff = max - min; TEAM LinG - Live, Informative, Non-cost... The Fortune Teller: Random Numbers, Conditionals, and Arrays There is one more operator that you need to learn, simply called the conditional, or ternary operator The conditional operator (? :) uses the Boolean value of one expression to decide which of the two other expressions should be evaluated The syntax is as follows: Chapter 3 1010 & 1100 JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 74 Java Programming . Statements … … Java Statements … … Java Statements … … Java Statements … FIGURE 3.9 The flowchart shows that a Java program executes one of two sets of statements depending on the value of the condition. JavaProgAbsBeg-03.qxd. type. Condition false if true … Java Statements … … Java Statements … … Java Statements … FIGURE 3.7 This flow chart shows how conditions affect the flow of the program. If the condition is true, some Java statements. allows for execution of a conditional choice of two state- ments, executing one or the other but not both. The syntax is as follows: if (condition) { java_ statements _for_ true_condition; } else { java_ statements _for_ false_condition; } If