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

发布于:2024-06-26 ⋅ 阅读:(129) ⋅ 点赞:(0)

一、习题介绍

第三章

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?

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 < 20: 在 Java 中,可以使用  java.util.Random  类来生成随机数。例如:

Random rand = new Random();

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

b. 生成一个随机整数i,使得 10 ≤ i < 20: 要生成一个在特定范围内的随机数,可以先生成一个在 0 到 19 之间的随机数,然后将其加到 10 上:

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 <= 100) || num < 0;

3.38

True or false? All the binary operators except = are left associative.

3.38对还是错?除=外的所有二元操作符都是左结合的。

答:错误。这个陈述是不正确的。在 Java 中,大多数二元操作符确实是左结合的,但也有一些是右结合的。例如,赋值操作符( = 、 += 、 -=  等)是右结合的。这意味着当多个赋值操作符出现在同一个表达式中时,它们从右向左进行求值。例如:

int a = 1;

int b = 2;

int c = (a = b) = 3; // 这里 a = b 先求值,然后 (a = b) = 3 再求值

在这个例子中, b  的值首先赋给  a ,然后  a  的值(现在是 2)再赋给  c 。所以最终  c  的值是 2,而不是 3。

 结语

唯有梦想才配让你不安

唯有行动才能解除你的不安

!!!     


网站公告

今日签到

点亮在社区的每一天
去签到