问答题
[说明]
本程序的功能是产生一个抽奖游戏中的随机数组合。抽奖的规则是从自然数1至50中无重复抽取6个数。为了保证抽取的无重复性,将50个自然数放在数组source中。每抽取了一个数,就用数组的最后一个数来改写这个被抽中的数,并把数组的长度减1。为使输出更为清晰,把抽取出来的6个数放在数组target中,经过排序(Arrays类中的sou方法实现排序)然后输出。注:Math.random方法返回一个在0(包含)到1(不包含)之间的随机浮点数。
[Java代码]
import java. util. *;
public class DrawOut
{ public static void main (String[ ] args) {
int n =50;
int k =6;
int[ ] source = new int[n];
for(int i=0; i <{{U}} (1) {{/U}};i++)
source[i] = i + 1;
int[ ] target = new int[k];
//将抽中的数字从source数组中取出,放入到target数组
for (int i = 0; i <{{U}} (2) {{/U}}; i+ +) {
int r = (int) (Math. random() *{{U}} (3) {{/U}});
target[i] = source[r];
.... [r] ={{U}} (4) {{/U}};
{{U}} (5) {{/U}};
}
Arrays. sort(target);
for (int i = 0; i < target, length; i + + )
System. out. prinfln ( target [i] );
}
}
【正确答案】
【答案解析】(1)source. length (2)target. length (3)n
(4)Source[n-1] (5)n--
本处for循环的功能是将自然数1至50顺序放到source数组中。数组的下标从。开始,上标是 source. length;
(2)本处for循环的功能是将从source数组中取出的数字放入target数组。数组的下标从0开始,上标是tar- get. length;
(3)Math. random方法返回一个在0(包含)到1(不包含)之间的随机浮点数,乘以n(此处值为50)是为了产生一个。至49之间的整数作为从source数组中取数字的下标;
(4)本行代码的功能是把source数组的最后一个数字来改写这个被抽中的数字;
(5)本行代码的功能是调整数组source的大小,将数组长度n减1。