JAVA期末速成库(3)第三章

06-26 1169阅读

一、习题介绍

第三章

Check Point:P88  3.16,3.19,3.38

二、习题及答案

3.16

a. How do you generate a random integer i such that 0 … i 6 20?

JAVA期末速成库(3)第三章

b. How do you generate a random integer i such that 10 … i 6 20?

c. How do you generate a random integer i such that 10 … i … 50?

d. Write an expression that returns 0 or 1 randomly.

3.16

a.如何生成一个随机整数i使0…i 6 20?

b.如何生成一个随机整数i,使10…i 6 20?

c.如何生成一个随机整数i,使得10…i…50?

d.写一个随机返回0或1的表达式。

答:3.16 如何生成一个随机整数i

a. 生成一个随机整数i,使得 0 ≤ i

Random rand = new Random();

int i = rand.nextInt(20); // 生成的随机数在 0 到 19 之间

b. 生成一个随机整数i,使得 10 ≤ i

int i = 10 + rand.nextInt(10); // 生成的随机数在 10 到 19 之间

c. 生成一个随机整数i,使得 10 ≤ i ≤ 50: 要生成一个在闭区间 [10, 50] 内的随机数,可以这样:

int i = 10 + rand.nextInt(41); // 生成的随机数在 10 到 50 之间

d. 随机返回0或1的表达式: 可以使用  Random  类生成一个随机的布尔值:

int randomValue = rand.nextInt(2); // 生成的随机数是 0 或 1

3.19

(a) Write a Boolean expression that evaluates to true if a number stored in variable

num is between 1 and 100. (b) Write a Boolean expression that evaluates to true if

a number stored in variable num is between 1 and 100 or the number is negative.

3.19

(a)编写一个布尔表达式,如果一个数字存储在变量中,计算结果为true

Num在1到100之间。(b)写一个布尔表达式,如果求值为真

答:存储在变量num中的数字介于1到100之间,或者该数字是负数。

boolean isBetween1And100OrNegative = (num >= 1 && num

VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]