1. Trang chủ
  2. » Công Nghệ Thông Tin

Java Programming for absolute beginner- P5 pptx

20 345 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Java Programming For The Absolute Beginner
Trường học Standard University
Chuyên ngành Computer Science
Thể loại Bài tập
Năm xuất bản 2003
Thành phố City Name
Định dạng
Số trang 20
Dung lượng 485,84 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The java.util.Random Class Another way that you can generate random numbers is by using the Randomclass in the java.utilpackage.. double nextDouble Returns a random double value ranging

Trang 1

J a

s o

l ut

n e

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 Randomclass

in the java.utilpackage The Randomclass 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

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).

T A B L E 3 1 S O M E J A V A U T I L R A N D O M M E T H O D S

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-MakerUtilapplication demonstrates how this is done Take a look at the source code:

/*

* NumberMakerUtil

* Uses java.util.Random to generate random numbers

*/

Trang 2

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 NumberMakerUtilprogram is displayed in Figure 3.3

59

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 Randomobject:

Random rand = new Random();

Trang 3

This makes randan instance of the Randomclass and you use it to generate ran-dom values Now that you have created rand, you can call the methods defined

in the Randomclass 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 iLimitto be an intwhose 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 Tapossi-ble 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 Randommethods 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 Randomobject 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 AmIRandomprogram, which demonstrates the concept

of the seed and pseudorandom numbers

/*

* AmIRandom

* Demonstrates the concept of a seed and pseudorandom numbers

*/

H I N T 60

J a

s o

l ut

n e

Trang 4

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 rand3to 12345 You set rand1’s seed by putting that number in as a parame-ter when creating the Randomobject

Random rand2 = new Random(12345);

You set rand3’s seed after it was already assigned its Randomobject 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

Trang 5

The Math Class

You used the Math.random() method to generate random numbers Now you learn more about the Mathclass The Mathclass 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 Mathclass in the Java documentation for more detailed information

The MathClassTestapplication 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:

Randomobject yourself On the other hand, I find it easier to use the Randomclass

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 doublevalues and perform mathematical operations

62

J a

s o

l ut

n e

FIGURE 3.4

This is the output of the AmIRandom

application rand2

and rand3 will always generate the same output.

I N THE R EAL W ORLD

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!

Trang 6

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) Roundsfto the nearest int value

Math.round(double d) Roundsdto 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) Convertsd(in radians) to degrees

Math.toRadians(double d) Convertsd(in degrees) to radians

T A B L E 3 2 M A T H C L A S S M E T H O D S

FIGURE 3.5

The

MathClassTest

application output.

Trang 7

J a

s o

l ut

n e

I N THE R EAL W ORLD

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 doublevalues ranging from 0.0to 1.0 You also know how to use the java.util.Randomclass to gener-ate random numbers You can use it to genergener-ate all possible intand longvalues,

as well as floatsand doublesranging from 0.0to 1.0 You also know how to have limited control of random intvalues using the Random.nextInt(int n)method, which gives you a range from 0to (n-1) This section covers how to generate ran-dom numbers that fit within a specific range

Trang 8

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, dis assigned a random value ranging from 0.0(inclusive) to

45.0(exclusive) You can do the same thing when using Randommethods 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.0to 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.0and 1.0 This value is multiplied by 180because 212.0 – 32.0

= 180.0 The difference between the lower and upper limit ranges from 0.0to

180.0 When 32is added to that value, the range becomes 32.0to 212.0, just like you needed

If you need a range of integers; for example, from 1to 10inclusive, you do it this way:

int n = (int) (Math.random() * 10 + 1);

This code assigns a random intranging from 1 to 10inclusive Math.random()

generates a random number from 0.0to 1.0; the range is multiplied by 10and becomes 0.0to 10.0 Add 1to that and now it ranges from 1.0to 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 DiceRollerapplication 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

Trang 9

* 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() randomis a Randomobject, and die1and die2are 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 1to 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

s o

l ut

n e

Trang 10

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 0and 5inclusive, 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 myRandomNumberis 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 trueonly when the number on the left side is equal to the number on the right side The syntax for the ifstatement is as follows:

if (condition) {

java statements;

}

The ifkeyword is followed by a condition within parentheses The statements that execute ifthe condition is true are placed within the braces Recall that a

67

FIGURE 3.6

The DiceRoller

application is

a simulation of rolling dice.

Ngày đăng: 03/07/2014, 05:20

TỪ KHÓA LIÊN QUAN